xhr的send方法以及node如何处理get和post数据

原由:看了阮一峰老师的关于上传文件的文章,进行测试,在使用xhr对象的send方法时遇到问题。node

遇到的问题是使用send方法传送过去的数据,在node后台没法接收,通过不少次测试,怀疑是否是send与node不兼容致使。ajax

因此使用了jq的ajax方法进行测试,app

$("#sub").click(function(){
        $.ajax({
            url:"/upload",
            data:"foo=123",
            type:"POST"
        })
    })

发现post过去的数据可使用req.body接收。post

由于jq的ajax方法的原生即是xhr对象,因此基本排除send方法与node不兼容的说法。测试

以后查阅资料发现,原来使用send方法时,若是是get请求则直接写open和send便可,ui

可是假设是post方法传数据给后台,则须要加url

xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded;charset=UTF-8");

不然post过去的数据没法被正常接收。spa

 

补充:若是使用get方法,基本用法应该以下:code

 var xhr=new XMLHttpRequest();
 xhr.open("GET","upload?username=qiangzi&password=123";
xhr.send(null);

其中的url能够拼接字符串从而达到传参。orm

后台的node接收get数据以下:

var url=require("url");
var querystring=require("querystring");

exports.upload=function(req,res){

    var body=req.url;
    //获得的是一段字符串
    //  /?username=qiangzi&password=123

    var urlObj=url.parse(body);
    //把url解析成为对象
    //Url {
    //    protocol: null,
    //    slashes: null,
    //    auth: null,
    //    host: null,
    //    port: null,
    //    hostname: null,
    //    hash: null,
    //    search: '?username=qiangzi&password=123',
    //    query: 'username=qiangzi&password=123',
    //    pathname: '/',
    //    path: '/?username=qiangzi&password=123',
    //    href: '/?username=qiangzi&password=123' }
    
    var queryStr=urlObj.query;
    //得到传值部分

    //因为传的值是字符串,因此想办法变成对象,此处使用的是node自带的querystring方法,需引入
    var queryObj = querystring.parse(queryStr);
    //切割成对象以后咱们就能够获取咱们想要的部分.
  console.log(queryObj)

  //{ username: 'qiangzi', password: '123' }
};

 

post方法:

var xhr=new XMLHttpRequest();
xhr.open("POST","upload");
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded;charset=UTF-8");
xhr.send("user=qiangzi");

后台接收post数据:

exports.upload=function(req,res){
    console.log(req.body)  //{ user: 'qiangzi' }
};
相关文章
相关标签/搜索