相信大家在平時學習或工作中請求接口時遇到過這種提示:
Paste_Image.png
出現這種情況就是跨域了,由于安全方面的原因, 客戶端js使用xmlhttprequest
只能用來向來源網站發送請求,比如在www.readlog.cn下去請求test.readlog.cn的數據,都是不行的.
解決辦法 在后臺添加:
res.header('Access-Control-Allow-Origin','*');
app.js代碼 :
var express = require('express');
var app = express();
app.use(function(req,res,next){
res.header('Access-Control-Allow-Origin','*');//添加這句話就可以正常返回數據了
next();
})
app.get('/getData',function(req,res){
res.send({'test':'this is a test data'})
})
app.listen(8888,function(){
console.log('run server');
})