node跨域有很多方法
1、引入 中间件cors 我觉的最好的方法
var express=require('express'); var cors=require('cors'); var app=express(); app.use(cors({ origin:['http://localhost:8080'], //允许这个域访问 methods:['GET','POST'], //只允许get post allweHeaders:['Conten-Type','Autorization'] //只允许带这两种请求头的链接 })) //一定要放在请求前 app.use('/', index); app.use('/users', users);
2、允许了所有的跨域请求
var express = require('express'); var app = express(); var http=require('http'); 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"); if (req.method == 'OPTIONS') { res.send(200); } else { next(); } });