get请求和post请求

228 阅读1分钟

数据请求

1.使用 npm init 初始化 npm(node package manager)包管理工具 1.PNG

2.创建package.json

在初始化之后,一直按回车出现下列字符 2.PNG 则package name只能含有对url友好的字符,也不能出现大写字母,直至出现It this OK?3.PNG

3.下载npm模块

初始化完了之后下载数据请求的基础模块npm install express,下载完之后目录列表会有一个node_modules文件夹 4.PNG

4.创建一个index.js文件,在文件内引入数据请求基础模块express,创建数据请求实例对象web,同时设置网站只允许自己人来访问,(即建一个静态资源文件夹1.1,让所有前端代码放入这个文件夹中,只允许这个文件夹以内的请求来访问后台接口,其他请求不允许访问后台接口) 5.PNG

5.get请求

前端代码

function getHan(){
            var xhr = new XMLHttpRequest()
            xhr.open('get' , '/info')
            xhr.send()
            xhr.onreadystatechange = function(){
                if(xhr.readyState == 1){
                    // console.log('数据已传给服务器,服务器未返回给前端');
                }
                 if(xhr.readyState == 2){
                    // console.log('数据已传给服务器,服务器开始返回给前端');
                }
                 if(xhr.readyState == 3){
                    // console.log('数据已传给服务器,服务器已返回部分数据给前端');
                }
                 if(xhr.readyState == 4){
                    // console.log('服务器已返回全部数据');
                }

后端代码

web.get('/info',function( req ,res){
     console.log(req.query)
     res.send('')
})

6.post请求

前端代码

function postHan(){
            var xhr = new XMLHttpRequest()
            xhr.open('post' , '/login')
            xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
            xhr.send()
            xhr.onreadystatechange = function(){
                if(xhr.readyState == 1){
                    // console.log('数据已传给服务器,服务器未返回给前端');
                }
                 if(xhr.readyState == 2){
                    // console.log('数据已传给服务器,服务器开始返回给前端');
                }
                 if(xhr.readyState == 3){
                    // console.log('数据已传给服务器,服务器已返回部分数据给前端');
                }
                 if(xhr.readyState == 4){
                    // console.log('服务器已返回全部数据');
                }
            }
        }

后端代码,post请求需要先在后端引入body-parser模块

13.png

web.post('/login',function( req ,res){
     console.log(req.body)
     res.send('')
})