我使用节点js读取/处理geojson文件和asp.net MVC来查看地图,但我得到了这个错误
从源'https://company.com/api/v1/file?id=1&d=1661924420‘访问https://company.com/api/v1/file?id=1&d=1661924420 'http://localhost’已被CORS策略阻止:请求标头字段内容类型在飞行前响应中不被访问控制允许标头所允许。
节点JS码
const express = require('express')
const cors = require('cors');
const app = express()
app.get(`/api/v1/file`, cors(), (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);
}
})
})ASP.NET MVC中的视图代码
<p id="result">Checking..</p>
<script>
$(function () {
TestFunction();
});
function TestFunction() {
var url = "@Url.Content("https://company.com/api/v1/file")";
$.ajax({
url: url,
headers: {
'Content-Type': 'application/json'
},
type: "GET", /* or type:"GET" or type:"PUT" */
dataType: "json",
data: {
id: 1,
d: Math.floor((new Date()).getTime() / 1000)
},
success: function (result) {
$("#result").html("success");
},
error: function () {
$("#result").html("error");
}
});
}
</script>此外,我还使用ARR访问我的节点js应用程序。这是我的webconfig
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="ReverseProxyInboundRule1" stopProcessing="true">
<match url="(.*)" />
<action type="Rewrite" url="http://localhost:6001/{R:1}" />
</rule>
<rule name="ReverseProxyInboundRule2" stopProcessing="true">
<match url="(.*)" />
<action type="Rewrite" url="http://localhost:6001/{R:1}" />
</rule>
</rules>
</rewrite>
<httpProtocol>
<customHeaders>
<clear />
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
<system.web>
<compilation debug="false" />
<httpRuntime executionTimeout="1000" />
</system.web>
</configuration>发布于 2022-08-31 06:04:49
您正在从ASP .NET页面对NodeJS API进行HTTP调用。您的NodeJS应用程序需要允许来自承载/运行ASP .NET页面的域的cors请求。您可以使用此npm包来允许请求。
步骤:
cors包安装在NodeJS项目的根文件夹中。npm安装cors
您可以按照文档来允许自定义来源和方法来限制访问。
https://stackoverflow.com/questions/73551392
复制相似问题