node.js - 如何为 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 请求?
解决方案
您的 cors 错误消息清楚地表明您在发出请求时需要使用 http
$.ajax({
type: "GET",
url: "http://localhost:3000/send",
beforeSend:function(){
$(".loading_msg").hide();
},
complete:function(){
$(".loading_msg").show();
}
});
推荐阅读
- salesforce - 无法从 VALUE_STRING 值 1,9459.1650 反序列化货币实例,或者请求可能缺少必填字段
- ruby-on-rails - 在 Rails 中使用 rswag - 索引响应(数组)的语法是什么?
- java - Maven 命令行按名称从远程存储库列表中排除下载
- java - Hibernate 在数据库中插入额外的记录
- python - 分类到序数转换,我应该使用什么值?
- reactjs - this.setState 直到函数调用两次才更新状态
- arrays - 使用 numpy 将某些行添加到数组
- javascript - jsonwebtoken, jwt 在提供无效令牌时使我的应用程序崩溃,即使 errorHandler 中间件捕获了错误
- json - 在反应的json数组中动态添加和切换showmore/less
- angular - 如何处理来自 api 响应的数据,然后以角度同步返回布尔值?