0
votes

When trying to make a POST to a mongo db, I get no response from the page. Things work just fine when I run them on the aws ubuntu server with things being saved properly to the database, but when run from a non local machine nothing happens. To be clear: I can access my url from any machine but the cannot POST from any machine, POST only works on the machine ive set up my EC2 with.

I have the following set up regarding my port config:

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)

Every time I click submit on the POST, I receive this (see image) error in the Network tab of the console. When I go and look at the headers for the failure, I see:

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

2
whats the error message, this looks like a cors (cross-origin resource sharing) issue to meArun K
Are you running express on nodejsArun K

2 Answers

2
votes

You have to setup cors in your nodejs api end point. Setting the header Access-Control-Allow-Origin to * will allow the requests to be sent from any domain. You can also set specific domains.

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();
});
2
votes

To add to what @Arunmainthan was saying, you can actually just do app.use(cors()); after requiring cors and it will yield the same results