如何在Node.js与ASP.NET MVC间配置Access-Control-Allow-Headers解决CORS问题
解决CORS跨域错误:允许Content-Type请求头
问题原因
浏览器拦截请求是因为OPTIONS预飞请求的响应中,Access-Control-Allow-Headers未包含Content-Type字段。另外你的GET请求无需设置Content-Type: application/json,这也是触发预飞请求的诱因之一。
方案1:修正前端AJAX请求(最简方案)
GET请求的参数通过URL传递,不需要手动设置Content-Type请求头,直接移除该配置即可避免预飞请求:
<p id="result">Checking..</p> <script> $(function () { TestFunction(); }); function TestFunction() { var url = "@Url.Content("https://company.com/api/v1/file")"; $.ajax({ url: url, type: "GET", dataType: "json", data: { id: 1, d: Math.floor((new Date()).getTime() / 1000) }, success: function (result) { $("#result").html("success"); }, error: function () { $("#result").html("error"); } }); } </script>
方案2:配置Node.js的CORS中间件
若必须保留Content-Type请求头,需在Express的cors中间件中明确允许该请求头:
const express = require('express') const cors = require('cors'); const app = express() // 配置允许Content-Type请求头 const corsOptions = { allowedHeaders: ['Content-Type'] }; app.get(`/api/v1/file`, cors(corsOptions), (req, res, next) => { const { id } = req.query console.log(`Request Params id: ${id}`); pathFile = `./files/uploads/${id}.geojson`; readFile(pathFile,'utf8', (err, jsonmap) =>{ console.log(`Reading File: ${pathFile}`); if(err){ console.log(err); return res.status(404).send('No such file found!'); }else{ var g = JSON.parse(jsonmap); return res.status(200).json(g); } }) })
如需支持更多请求头,可扩展配置:
const corsOptions = { allowedHeaders: ['Content-Type', 'Authorization', 'Accept'] };
方案3:通过ARR的web.config配置全局CORS头
利用反向代理的web.config直接添加响应头,覆盖所有请求的CORS规则:
修改web.config的<customHeaders>节点:
<httpProtocol> <customHeaders> <clear /> <add name="Access-Control-Allow-Origin" value="*" /> <!-- 允许Content-Type请求头 --> <add name="Access-Control-Allow-Headers" value="Content-Type" /> <!-- 可选:允许常用请求方法 --> <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS" /> </customHeaders> </httpProtocol>
注意:Node.js的cors中间件和ARR的自定义头不要同时配置,避免出现重复响应头导致冲突。
内容的提问来源于stack exchange,提问作者Yuu
相关产品推荐
相关产品推荐

