前端代碼javascript
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爲例html
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前端