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

express cors not working
node js cors allow all
access-control-allow-origin
node js cors proxy
has been blocked by cors policy node js
express static cors
express cors multiple origins
express() app options

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.

This is because you are requesting a not-so-simple request, meaning it needs to handle preflight request which is made as an HTTP OPTIONS request (so be sure your server is able to respond to this method). The preflight request is a way of asking permissions for the actual request, before making the actual request. The server should inspect the two headers above to verify that both the HTTP method and the requested headers are valid and accepted.

How to Enable CORS in Node.js Without Express CORS Middleware, How to allow cross site requests by setting up CORS. If you are using Node.js and Express as a framework, use the CORS middleware package. If you hit /​without-cors with a fetch request from a different origin, it's going  How to Enable CORS in Node.js Without Express CORS Middleware. It’s very easy to simply install the cors middleware to handle all the CORS stuff while using Node.js as your backend. This, however, leaves you with a very superficial understanding of how the Cross-Origin Resource Sharing mechanism works.

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);

Express cors middleware, This is easier and faster way to enable CORS in your application. app.js var express = require('express'); var cors = require('cors'); You can achieve the same, without requiring any external module if you are fine adding a  cors. CORS is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options.. Follow me (@troygoode) on Twitter! Installation

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

Handling CORS in Express, Cross-origin resource sharing (CORS) allows AJAX requests to skip the In this post I will show you how to enable CORS support in Express. I… Sessionless Authentication using JWTs (with Node + Express + Passport JS). To enable CORS without an external module or npm package, we have to simply write a few lines of the code in a server file. // enable CORS without external module 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(); });

How to add CORS functionality to your NodeJS web app, Acheiving CORS via a Node HTTP Server. cors.js. // Create our server Set CORS headers setHeader('Access-Control-Allow-Headers', req.header.origin); If you using Chrome and your not sure what headers are being requested, use​  To enable CORS in Node Js simply add below line of code. It will set a header on your response in result CORS are enabled.

Using CORS in Express - Alexis Hevia, ExpressJS app on node.js, do the following with your routes: app.use(function(​req, res, next) { res.header("Access-Control-Allow-Origin", "YOUR-DOMAIN. Enabling CORS in Express. Install cors npm package in Express and Node app. npm install cors --save Import express npm package and use cors as a middleware in a node server. That is how we can enable the CORS in an Express. // server.js or app.js const express = require ('express'); const cors = require ('cors'); const app = express (); app. use (cors ());

Acheiving CORS via a Node HTTP Server · GitHub, Learn how to enable CORS for your cross-domain requests in Node.js with these example code snippets. Simply using this line of code to set a header on your response will enable CORS var express = require('express');. Express.js is one of the most popular node.js frameworks for serving websites or building APIs. This article is about how to enable Cross Origin Resource Sharing, also known as CORS. For that we need to set the correct headers in the response, which allow a browser to make use of the data from any domain. Visit the demo project on github. A

Comments
  • Correct, use is not a method of server - perhaps this will shed some light - seeing as node cors is middleware for Express (or Connect) - it's not surprising your code won't work as is
  • @JaromandaX gist.github.com/balupton/3696140 failed to work
  • You did it wrong
  • still getting the same error I bet ... seeing as you still do http.createServer(app).listen(3000).use(cors()); ... derp
  • @JaromandaX oh just didn't update here. I am getting 405 error now.