Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow CORS with Node.js (without using Express)

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.

like image 705
Aero Wang Avatar asked Jun 07 '17 06:06

Aero Wang


People also ask

How do I enable CORS in node JS?

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.

How do I resolve cross-origin issues in node JS?

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.

Can you use Express without node?

You cannot use Express without NodeJS by definition so you have to deploy your backend somewhere else in you want to use it.


2 Answers

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);
like image 150
Black Mamba Avatar answered Oct 13 '22 20:10

Black Mamba


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

like image 41
jony89 Avatar answered Oct 13 '22 19:10

jony89