Adding CORS headers to my NodeJS ExpressJS API but not working

Viewed 286

I have this API that I have created that is called from an angularJS app through a POST request. Everything is working fine except that, because the API and the app are not hosted on the same server, I have this Cross-Origin Resource Sharing (CORS) mechanism blocking the post request, unless I activate the CORS add-on in Chrome, which I would like to avoid.

Apparently, the solution lies in the headers, and I have found some very promising information, but there is something I must be doing wrong because I can't seem to make it work.

Here is my code:

  1. parentheses.js (where my post request happens)

    const parenthesesChecker = require('./checker.js');
    
    const express = require('express'), bodyParser = require('body-parser');
    const router = express.Router();
    
    router.use(bodyParser.json());
    
    router.post('/', (req, res, next) => {
      res.setHeader('Access-Control-Allow-Origin', '*');
      res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
      res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
      const stringCheck = ({
        string: req.body
      });
      if (parenthesesChecker(stringCheck.string.string).result === true) {
        res.status(200).json({
          "isValid": true
        });
      } else {
        res.status(200).json({
          "isValid": false,
          "errorDetails": {
              "preceedingParentheses": `${parenthesesChecker(stringCheck.string.string).preceeding}`,
              "erroneosParentheses": `${parenthesesChecker(stringCheck.string.string).erroneos}`
          }
        });
      };
    });
    
    module.exports = router;
    
  2. app.js

    const express = require('express');
    const app = express();
    
    const parenthesesRoutes = require('./parentheses');
    app.use('/parentheses', parenthesesRoutes);
    
    module.exports = app;
    
  3. server.js

    const http = require('http');
    const app = require('./app')
    
    const port = process.env.PORT || 3000;
    
    const server = http.createServer(app);
    server.listen(port);
    

When I try to use the app that makes the post request to the API, without activating the CORS add-on in my chrome browser, I get this error message in the console:

Access to XMLHttpRequest at 'https://parentheses-api.herokuapp.com/parentheses' from origin 'http://127.0.0.1:8080' 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.
0 Answers
Related