问题:
1、本地localhost跨域连接nodejs服务器时Chrome报错:(项目用的express框架)
2、无法接收put请求的参数
解决办法:
//app.js
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", ' 3.2.1')
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
或者引入cors
npm install cors
//app.js
var cors = require('cors');
app.use(cors());
知识点
header头三件套
header(‘Access-Control-Allow-Origin :’.$origin); //允许的域名( * 所有域)
header(‘Access-Control-Allow-Methods : POST’); //允许的方法
header(‘Access-Control-Allow-Headers : x-requested-with , content-type’); //服务器支持的头信息
~ end