当尝试向 mongo 数据库发送 POST 时,我没有从页面得到任何响应。当我在 aws ubuntu 服务器上运行它们时,一切正常,并且内容正确保存到数据库中,但是当从非本地计算机运行时,什么也没有发生。需要明确的是:我可以从任何机器访问我的 url,但不能从任何机器 POST,POST 仅适用于我设置 EC2 的机器。
我对端口配置进行了以下设置:
Connected to the db -->
mongoose.connect("mongodb://x.xxx.xxx.xx:27017/yoga"); Have port 27017 open (as well as 5000 and
3000) to all 0.0.0.0/0 traffic And have the IpBind (in the /etc/mongod.conf) set to x.xxx.xxx.xx
(have also tried 0.0.0.0 and the all binding flag command)
每次我在 POST 上单击“提交”时,我都会在控制台的“网络”选项卡中收到此(参见图片)错误。当我查看失败的标题时,我看到:
Request URL: http://localhost:5000/ Referrer Policy: no-referrer-when-downgrade Provisional headers are shown Access-Control-Request-Headers: content-type Access-Control-Request-Method: POST Origin: http://youthrivingwellness.com Referer: http://youthrivingwellness.com/ User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36
最佳答案
你必须在你的nodejs api端点中设置cors。将 header Access-Control-Allow-Origin
设置为 *
将允许从任何域发送请求。您还可以设置特定域。
const express = require('express');
const cors = require('cors');
const app = express();
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();
});
关于node.js - POST 到 AWS EC2 Mongodb 数据库在生产中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59148553/