如何为nodejs Express服务器启用CORS?

问题描述 投票:0回答:2

我试图在我的前端使用Ajax请求:

$.ajax({
    type: "GET",
    url: "localhost:3000/send",
    beforeSend:function(){
             $(".loading_msg").hide();
        },
    complete:function(){
             $(".loading_msg").show();
        }
});

但是当我加载包含脚本的页面时,我收到以下错误:

来自'http://localhost:3000'的'localhost:3000 / send'访问XMLHttpRequest已被CORS策略阻止:仅对协议方案支持跨源请求:http,data,chrome,chrome-extension,https。

未选中runtime.lastError:在收到响应之前关闭消息端口。

我尝试了很多东西,比如添加一个中间件来表达:

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
     next();
   });

这没什么区别。

我也尝试过安装cors npm包并做到了

const cors=require('cors')
app.use(cors())
app.options('*', cors());

这没有任何区别。

我还尝试通过添加https://来更改ajax URL

 url: "https://localhost:3000/send",

虽然这确实消除了CORS错误,但它给了我另一个错误:

获取https://localhost:3000/send net :: ERR_SSL_PROTOCOL_ERROR

在使用localhost时如何从Nodejs表达服务器发送Ajax请求?

node.js express
2个回答
2
投票

您的cors错误消息清楚地表明您在发出请求时需要使用http

$.ajax({
    type: "GET",
    url: "http://localhost:3000/send",
    beforeSend:function(){
             $(".loading_msg").hide();
        },
    complete:function(){
             $(".loading_msg").show();
        }
});

0
投票

你需要这个受欢迎的包,CORS。另一种解决方法是使用快速服务器向您的webapp添加后端,并使用axios / request npm包使用http从API服务器请求数据,然后您将不会遇到任何CORS问题。

© www.soinside.com 2019 - 2024. All rights reserved.