Reputation: 145
Im trying to send a POST from a client connected to this server to a external URL. I get a lot of 'CORS' errors. Im pretty sure that it's because i haven't allowed 'Access-Control-Allow-Origin' and etc on my Node.JS server. But i don't know how to do it. I have found another answers on the web, but none of them solved my problem. Here is my server:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
const { instrument } = require('@socket.io/admin-ui')
var bodyParser = require('body-parser')
var clientesConectados = [];
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.get('/', function(req, res){
//send the index.html file for all requests
res.sendFile(__dirname + '/index.html');
});
app.post('/', (request, res) => {
console.log("********************");
console.log(" >POST RECEBIDO!!");
console.log(res);
postData = request.body;
io.emit('message',postData);
console.log(postData);
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Upvotes: 0
Views: 3573
Reputation: 537
Install cors package in your application
npm install cors
And then add these two lines in there
var cors = require("cors");
app.use(cors())
Else there are ways that set through header or you could use a proxy in your frontend but using cors package is simpler
Upvotes: 1
Reputation: 114
Install npm package called cors
After installing, on your file add this line app.use(cors())
will solve your issue of cors error I hope.
Upvotes: 0