【发布时间】:2019-08-14 16:37:36
【问题描述】:
我正在尝试在前端使用 Ajax 请求:
$.ajax({
type: "GET",
url: "localhost:3000/send",
beforeSend:function(){
$(".loading_msg").hide();
},
complete:function(){
$(".loading_msg").show();
}
});
但是当我加载包含脚本的页面时,我收到以下错误:
在 'localhost:3000/send' 从源访问 XMLHttpRequest 'http://localhost:3000' 已被 CORS 策略阻止:跨源 请求仅支持协议方案:http、data、chrome、 chrome 扩展,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/sendnet::ERR_SSL_PROTOCOL_ERROR
如何在使用 localhost 时从 Nodejs express 服务器发送 Ajax 请求?
【问题讨论】:
-
将
app.use(cors())放在哪里很重要。确保在安装任何路线之前拨打电话 -
@miyu
app.use(cors())是我所有的路线。 @Ashok 你链接到我自己的问题。