前端代碼
var xhr=new XMLHttpRequest();
xhr.open('POST','http://127.0.0.1:8081/ceshi',true);
xhr.onreadystatechange=function(){
if(xhr.readyState==4){//響應完畢后
if(xhr.status==200){//http狀態碼為200時
var result=xhr.responseText;//獲取ajax請求的文本內容
console.log(result);
}
}
}
xhr.setRequestHeader("Content-Type","application/json")
var a={name:123,data:"sss"};
var b=JSON.stringify(a);
xhr.send(b)
}
//此處有兩個坑
//坑1:有些ajax類庫中的代碼會影響服務器跨域設置
http://www.cnblogs.com/daishuguang/p/3971989.html
//坑2:如果設置Content-Type為application/json那么在服務端需要設置
//res.header("Access-Control-Allow-Headers", "Content-Type");
//並且請求會發送兩次,因為在跨域的時候,除了contentType為application/x-www-form-urlencoded, multipart/form-data或者text/plain外,都會觸發瀏覽器先發送方法為OPTIONS的請求。比如說,你原來的請求是方法方法POST,如果第一個請求返回的結果Header中的Allow屬性並沒有POST方法,
那么第二個請求是不會發送的,此時瀏覽器控制台會報錯,告訴你POST方法並不被服務器支持。
服務器代碼 此處采用node.js為例
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Headers", "Content-Type");
res.header("Access-Control-Allow-Methods","POST,PUT,GET,DELETE,OPTIONS");
res.header("Access-Control-Allow-Origin", "*");
res.header("X-Powered-By",' 3.2.1')
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}))
app.get('/', function (req, res) {
console.log("你好啊")
res.send('Hello World');
})
app.post('/ceshi',function(req,res){
console.log(req.body)
res.send("nihao")
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("服務器啟動成功", host, port)
})
參考文章http://www.jianshu.com/p/fddd19669ab3
