Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS issue with Restify

I have created a ReactJs app with a Node Api which uses Restify, but whatever I do I always have the error for POST method :

  • 405 (Method Not Allowed)
  • Access to fetch at 'http://localhost:3001/api/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I have tried everything I saw on Internet but I always have this issue.

To call the API, here is my code :

const request = new Request(url + 'login', {
    method: 'POST',
    body: JSON.stringify({ 'username' : username, 'password' : password }),
    headers: new Headers({ 'Content-Type': 'application/json' })
})
return fetch(request)
    .then(response => {
        if (response.status < 200 || response.status >= 300) {
            throw new Error(response.statusText);
        }
        return response.json();
    })
    .then(({ token }) => {
        localStorage.setItem('token', token);
    });

And I configure Restify like this :

const config = require('./config'),
  restify = require('restify'),
  errs = require('restify-errors');


var connection = config.db.get


const server = restify.createServer({
  name: config.name,
  version: config.version,
  url: config.hostname
});

server.use(restify.plugins.acceptParser(server.acceptable));
server.use(restify.plugins.queryParser());
server.use(restify.plugins.bodyParser());

server.use(
  function crossOrigin(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, OPTIONS, DELETE');
    res.header('Access-Control-Allow-Credentials', false);
    return next();
  }
);

server.listen(3001, function () {
  console.log('%s listening at %s', server.name, server.url);
});

server.post("/api/login", function (req, res) {
  res.send(200);
});

So I expect to receive a validation (code 200) after calling the Api, but I always have CORS issue.

Is there anything else to configure ?

Thanks for your help !!! :D

like image 855
Adz Avatar asked Jan 31 '26 18:01

Adz


1 Answers

You have to use corsMiddleware to avoid cors issue....write this code in your app.js file ...it should be work fine

var restify = require('restify');
var corsMiddleware = require('restify-cors-middleware');

var cors = corsMiddleware({
        preflightMaxAge: 5,
        origins: ['*'],
        allowHeaders:['X-App-Version'],
        exposeHeaders:[]
      });
/**
 * Initialize Server
 */
 var server = restify.createServer();

server.pre(cors.preflight);
server.use(cors.actual);
like image 140
Nisar Saiyed Avatar answered Feb 02 '26 10:02

Nisar Saiyed