node允許跨域以及獲取Ajax請求的引數
阿新 • • 發佈:2019-02-05
設定node後臺允許跨域請請求很簡單,在入口頁面app.js新增程式碼:
//設定跨域訪問
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
res.header("Access-Control-Allow-Methods" ,"PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1')
next();
});
再說下使用Ajax的post請求方式傳送的資料,在node伺服器端如何獲取:
在前臺頁面傳送post
必須注意以下幾點:
- 發給後臺服務端的資料格式必須為
json字串
- 必須規定
contentType:"application/json"
- 返回的資料設定為
dataType:'json'
這個不是必須的。
案例:
var qdata = {'name':'well','pad':"123"};
var fodata = JSON.stringify(qdata);//把資料轉換為字串
$.ajax({
url:'http://localhost:3800/news/about',
dataType:'json',
type:'GET',
data: fodata,
contentType:"application/json",
success: function(result){
console.log(typeof result)
console.log(result)
},
error :(error)=>{
console.log(error)
}
})
在服務端必須設定以下幾點:
- 安裝
body-parser
模組npm install body-parser --save
- 在app.js 也就是服務端的入口設定json 解析,無論在哪個文件獲取引數都必須在入口的頁面設定。
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
其次:使用get
方式相對比較簡單些。
引數可以是物件,可以是字串也不用設定型別,案例:
前臺頁面
function submit(){
var form = $('form').serialize();
var qdata = {name:'well', pwd:"123"};
$.ajax({
url:'http://localhost:3800/news/about',
dataType:'json',
type:'GET',
data: form, // form 和qdata 兩種資料都可以
success: function(result){
console.log(typeof result)
console.log(result)
},
error:(error)=>{
console.log(error)
}
})
}
服務端頁面:
router.get('/about', function(req, res) {
console.log(req.query.name);
res.send({status:200, error: 'message',data:''});
});