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' }
};
相關文章
相關標籤/搜索