总结一下近期遇到ajax跨域请求问题
业务场景描述:
- 移动端页面放在阿里云服务器
- 进入页面后, 需要访问另一个服务器的接口,ajax请求使用用GET,POST,PUT等方法
- 服务端需要进行cors配置
操作过程中出现的问题
- 发送PUT请求时,请求头的method变成OPTIONS, 且浏览器控制台给出提示:
Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.
对于出现OPTIONS请求的理解:
在跨域请求时,浏览器对于PUT,DELETE等方法,会先发送一次预检请求,该请求头的method就是OPTIONS,服务端需要对这个请求进行处理,浏览器得到服务端支持该请求时,才会发送真正的PUT请求。
服务器最终配置
//node跨域配置
app.all('*', function(req, res, next) {let reqOrigin = req.header["origin"];if (req.method === 'OPTIONS') {console.log(req.method)var headers = {};// IE8 does not allow domains to be specified, just the *// headers["Access-Control-Allow-Origin"] = req.headers.origin;headers["Access-Control-Allow-Origin"] = "*";headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";headers["Access-Control-Allow-Credentials"] = false;headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept";res.writeHead(200, headers);res.end();} else {console.log(req.method)res.header("Access-Control-Allow-Origin", "*");next()}
});//orapp.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.all
部分的代码需要放置在app.use
之前!
node的cors模块
问题解决完了发现node提供了解决跨域问题的cors模块。解决跨域问题非常方便,但是由于node服务器只是自己在本地搭建用于测试用,工作中是和java开发配合,所以没有用起来。
github链接:cors
示例代码:
var express = require('express')
var cors = require('cors')
var app = express()app.use(cors())app.get('/products/:id', function (req, res, next) {res.json({msg: 'This is CORS-enabled for all origins!'})
})app.listen(80, function () {console.log('CORS-enabled web server listening on port 80')
})