0

I have been trying to build a web application using NODE and React without Express router but I am getting a lot of issues with the CORS part since both node and react are running on different ports. I don't want to use express in this case since i want to use native http module provided by node, hence I am unable to use CORS middleware which is in the npm library.

I have tried every possible solution which would work for resolving the CORS issue but I am at a dead end now. I have shared my server side code below.

/*
 *   Main server file
 */

//Depenedencies
let https = require('https');
let url = require('url');
let fs = require('fs');
let handlers = require('./lib/handlers');
let stringDecoder = require('string_decoder').StringDecoder;
let decoder = new stringDecoder('utf-8');

//server object definition
let server = {};

//https certifications
server.certParams = {
    'key': fs.readFileSync('../lib/Certificates/serverKey.key'),
    'cert': fs.readFileSync('../lib/Certificates/serverCert.crt')
};

server.https = https.createServer(server.certParams, (req, res) => {

    server.unifiedServer(req, res);

});

//main server 
server.unifiedServer = (req, res) => {

    //converting url to url object
    let parsedUrl = url.parse("https://" + req.rawHeaders[1] + req.url, true);
    //constructing required params for handlers
    let method = req.method;
    let route = parsedUrl.pathname;
    let queryStringObject = parsedUrl.query;
    let headers = req.headers;

    //function specific params
    let requestBodyString = "";
    let chosenHandler;
    let requestObject = {};
    let responsePayload = {
        'Payload': {},
        'Status': ""
    };

    //streaming in the req body in case of post req
    req.on("data", function(chunk) {
        requestBodyString += chunk;
    });

    //this is called regardless of the method of the req
    req.on("end", function() {

        //this is specific to post req
        requestBodyString += decoder.end();

        requestBodyString = method == "POST" ? JSON.parse(requestBodyString) : {};

        //the request object sent to the handlers
        requestObject.method = method;
        requestObject.reqBody = requestBodyString;
        requestObject.queryObject = queryStringObject;

        chosenHandler = server.handlers[route] ? server.handlers[route] : server.handlers.notFound;        

        let headers = {
            "Access-Control-Allow-Origin" :  "https://localhost:3000/",
            "Access-Control-Allow-Methods" : "OPTIONS, POST, GET",
            "Access-Control-Allow-Headers" : "Origin, Content-Type"
        };

        chosenHandler(requestObject)
            .then((result) => {
                //post handler call
                responsePayload.Status = "SUCCESS";
                responsePayload.Payload = result;

                //send the data back
                res.writeHead(200,headers);
                res.write(JSON.stringify(responsePayload));
                res.end();
            }).catch((error) => {
                //error handler 
                responsePayload.Status = "ERROR-->" + error;

                //send the data back
                res.writeHead(200,headers);
                res.write(JSON.stringify(responsePayload));
                res.end();
            });
    });
};

//router definition
server.handlers = {
    '/login': handlers.login,
    '/signup': handlers.signup,
    '/checkUserName': handlers.checkUserName,
    '/checkEmail': handlers.checkEmail,
    '/notFound': handlers.notFound
};

//init function
server.init = () => {
    //start the https server
    //TODO--> Change this to handle changing port and env
    server.https.listen(5000, function() {
        console.log('The https server is listening on port 5000 in Development mode');
    });
};

//export the module
module.exports = server;

I am making a post request to test the connection but I am getting this evertime:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:5000/login. (Reason: CORS request did not succeed).

Can anyone please tell me what am I doing wrong?

Gilbert Gabriel
  • 422
  • 2
  • 8
  • 23

2 Answers2

1

Set the "Access-Control-Allow-Origin" header in the response stream object.

Try with the below snippet -

server = http.createServer(function(req,res){
    // Set CORS headers
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Request-Method', '*');
    res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
    res.setHeader('Access-Control-Allow-Headers', '*');
    if ( req.method === 'OPTIONS' ) {
        res.writeHead(200);
        res.end();
        return;
    }

    // ...
});

OR it that does not work, try using -


res.setHeader('Access-Control-Allow-Headers', req.header.origin);

shiva2492
  • 409
  • 3
  • 10
0

Use this middle ware after let decoder = new stringDecoder('utf-8');

var express    = require('express');
var app        = express();

var allowCrossDomain = function (req, res, next) {
      res.header('Access-Control-Allow-Origin', '*');
      res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
      res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
      res.header('Access-Control-Allow-Credentials', 'true');
      // intercept OPTIONS method
      if ('OPTIONS' == req.method) {
          res.status(200).send();
      } else {
          next();
      }
};


app.use(allowCrossDomain);

This is relevent for express framework.

Community
  • 1
  • 1
Darshana Pathum
  • 649
  • 5
  • 12