I tried answers from other questions and used (updated from https://gist.github.com/balupton/3696140):
var http = require('http');
var cors = require('cors');
http.createServer(app).listen(3000).use();
function app(request, response) {
response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Request-Method', '*');
response.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
response.setHeader('Access-Control-Allow-Headers', '*');
...
}
It returns: http.createServer(...).listen(...).use is not a function
After the update it runs but I am still getting 405 error on the client side.
Enable All CORS Requests If you want to enable CORS for all the request you can simply use the cors middleware before configuring your routes: const express = require('express'); const cors = require('cors'); const app = express(); app.
To solve this error, we need to add the CORS header to the server and give https://www.section.io access to the server response. Include the following in your index. js file. const cors = require('cors'); app.
You cannot use Express without NodeJS by definition so you have to deploy your backend somewhere else in you want to use it.
Here's detailed answer to add CORS without plugins: The code has been taken from here.
const http = require('http');
const port = 8080;
http.createServer((req, res) => {
const headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'OPTIONS, POST, GET',
'Access-Control-Max-Age': 2592000, // 30 days
/** add other headers as per requirement */
};
if (req.method === 'OPTIONS') {
res.writeHead(204, headers);
res.end();
return;
}
if (['GET', 'POST'].indexOf(req.method) > -1) {
res.writeHead(200, headers);
res.end('Hello World');
return;
}
res.writeHead(405, headers);
res.end(`${req.method} is not allowed for the request.`);
}).listen(port);
You don't want to use Express but yet trying to use it's middle-ware mechanism.
if
var server = http.createServer(app).listen(3000)
then server doesn't have the .use
function, the cors
module was designed as a middle-ware which means you need to use Express/Connect in order to use it.
You can keep being wihtout expressjs and find different ways than using cors
, for e.g see here https://gist.github.com/balupton/3696140
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With