首页 > 解决方案 > 如何为 nodejs Express 服务器启用 CORS?

问题描述

我正在尝试在前端使用 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 错误,但它给了我另一个错误:

GET https://localhost:3000/send net::ERR_SSL_PROTOCOL_ERROR

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

标签: node.jsexpress

解决方案


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

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


推荐阅读