1.处理服务器跨域问题(node-express)

方法1.设置app.all('*', function(req, res, next) {})

var express = require('express');
var app = express();
**
//设置跨域访问(添加这段)
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();
});
**
app.get('/getdata', function(req, res) {
    res.send({id:req.params.id, name: req.params.password});
});

app.listen(3000);
console.log('Listening on port 3000...');

方法2:引入cors模块(亲测,可以使用,有可能会提示缺少模块,缺少的就再去安装)
先使用npm install cors安装模块

//替换上面**里面的内容
**
// var cors = require('cors')
// app.use(cors())
**

你可能感兴趣的:(1.处理服务器跨域问题(node-express))