Cause: Read Nanyi's article about uploading files, testing, and encountering problems when using the Send method of the Xhr object.
The problem is that using the Send method to send past data, can not be received in the background of node, after many tests, suspected is not a send and node incompatibility caused.
So using the JQ Ajax method for testing,
$ ("#sub"). Click (function() { $.ajax ({ URL:"/upload", Data:"foo=123", type:"POST" }) })
The data that was found post past can be received using Req.body.
Since JQ's Ajax method is native to the XHR object, it basically excludes the idea that the Send method is incompatible with node.
After reviewing the data found that the original use of the Send method, if it is a GET request to write open and send directly,
But assuming that the Post method passes the data to the background, you need to add
Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
Otherwise, post past data cannot be received properly.
Add: If you use the Get method, the basic usage should be as follows:
var xhr=New XMLHttpRequest (); Xhr.open ("GET", "upload?username=qiangzi&password=123 ";
xhr.send (null);
Where the URL can be spliced string to reach the parameters.
The backend node receives the get data as follows:
varUrl=require ("url");varQuerystring=require ("QueryString"); Exports.upload=function(req,res) {varbody=Req.url; //get a string ///?username=qiangzi&password=123 varurlobj=Url.parse (body); //parse the URL into an object //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 '} varQuerystr=Urlobj.query; //Get the Transfer value Section //Since the value passed is a string, it is a way to become an object, using the QueryString method of node's own, which needs to introduce varQueryobj =Querystring.parse (QUERYSTR); //after cutting into objects, we can get the parts we want.
Console.log (Queryobj)
{username: ' Qiangzi ', Password: ' 123 '}
};
Post method:
var xhr=New XMLHttpRequest () xhr.open ("POST", "Upload"); Xhr.setrequestheader ( "Content-type", "Application/x-www-form-urlencoded;charset=utf-8"); Xhr.send ("User=qiangzi");
Background receive post data:
exports.upload=function(req,res) { Console.log (req.body)
{User: ' Qiangzi '}};
Xhr Send method and how node handles get and post data