receiving CORS error while running two servers on localhost





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







-1















I am trying to test an api call being made from reactjs to a node rest layer using axios. I am receiving the following CORS error when I look at the console message from Chrome. I see the following error "Access to XMLHttpRequest at 'http://localhost:5001/api/login' from origin 'http://localhost:5000' 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.". The weird thing is that the code in the catch block is getting called for both methods (the one in the LoginApi is for testing purposes) but the error variable in the catch parameter keeps giving a message saying "error is not defined" when I mouseover it. 1) How is that possible for error to be undefined, if I am in the catch block because an error occurred? 2) How am I getting CORS errors if I am running from localhost and how can I resolve for testing purposes?



Here is the method in my saga file:



function* login(params){
try {
const api = new LoginApi();
const response = yield call(api.login, params);
} catch (error) {
debugger;
yield put({ type: types.ERROR_OCCURRED, error });
}
}


Here is the method in LoginApi object that is getting called from yield call:



login = async (loginProps) => {
try {
let api = axios.create({
baseURL: 'http://localhost/5001',
timeout: 100000
});

return await api.post(`/api/login`, loginProps);
} catch (error) {
debugger;
throw error;
}
}









share|improve this question

























  • stackoverflow.com/questions/18642828/…

    – Vishal-Lia
    Jan 3 at 4:32











  • Why would an exception be caught and the error object, the parameter of the catch condition be undefined?

    – user1790300
    Jan 3 at 16:09


















-1















I am trying to test an api call being made from reactjs to a node rest layer using axios. I am receiving the following CORS error when I look at the console message from Chrome. I see the following error "Access to XMLHttpRequest at 'http://localhost:5001/api/login' from origin 'http://localhost:5000' 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.". The weird thing is that the code in the catch block is getting called for both methods (the one in the LoginApi is for testing purposes) but the error variable in the catch parameter keeps giving a message saying "error is not defined" when I mouseover it. 1) How is that possible for error to be undefined, if I am in the catch block because an error occurred? 2) How am I getting CORS errors if I am running from localhost and how can I resolve for testing purposes?



Here is the method in my saga file:



function* login(params){
try {
const api = new LoginApi();
const response = yield call(api.login, params);
} catch (error) {
debugger;
yield put({ type: types.ERROR_OCCURRED, error });
}
}


Here is the method in LoginApi object that is getting called from yield call:



login = async (loginProps) => {
try {
let api = axios.create({
baseURL: 'http://localhost/5001',
timeout: 100000
});

return await api.post(`/api/login`, loginProps);
} catch (error) {
debugger;
throw error;
}
}









share|improve this question

























  • stackoverflow.com/questions/18642828/…

    – Vishal-Lia
    Jan 3 at 4:32











  • Why would an exception be caught and the error object, the parameter of the catch condition be undefined?

    – user1790300
    Jan 3 at 16:09














-1












-1








-1








I am trying to test an api call being made from reactjs to a node rest layer using axios. I am receiving the following CORS error when I look at the console message from Chrome. I see the following error "Access to XMLHttpRequest at 'http://localhost:5001/api/login' from origin 'http://localhost:5000' 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.". The weird thing is that the code in the catch block is getting called for both methods (the one in the LoginApi is for testing purposes) but the error variable in the catch parameter keeps giving a message saying "error is not defined" when I mouseover it. 1) How is that possible for error to be undefined, if I am in the catch block because an error occurred? 2) How am I getting CORS errors if I am running from localhost and how can I resolve for testing purposes?



Here is the method in my saga file:



function* login(params){
try {
const api = new LoginApi();
const response = yield call(api.login, params);
} catch (error) {
debugger;
yield put({ type: types.ERROR_OCCURRED, error });
}
}


Here is the method in LoginApi object that is getting called from yield call:



login = async (loginProps) => {
try {
let api = axios.create({
baseURL: 'http://localhost/5001',
timeout: 100000
});

return await api.post(`/api/login`, loginProps);
} catch (error) {
debugger;
throw error;
}
}









share|improve this question
















I am trying to test an api call being made from reactjs to a node rest layer using axios. I am receiving the following CORS error when I look at the console message from Chrome. I see the following error "Access to XMLHttpRequest at 'http://localhost:5001/api/login' from origin 'http://localhost:5000' 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.". The weird thing is that the code in the catch block is getting called for both methods (the one in the LoginApi is for testing purposes) but the error variable in the catch parameter keeps giving a message saying "error is not defined" when I mouseover it. 1) How is that possible for error to be undefined, if I am in the catch block because an error occurred? 2) How am I getting CORS errors if I am running from localhost and how can I resolve for testing purposes?



Here is the method in my saga file:



function* login(params){
try {
const api = new LoginApi();
const response = yield call(api.login, params);
} catch (error) {
debugger;
yield put({ type: types.ERROR_OCCURRED, error });
}
}


Here is the method in LoginApi object that is getting called from yield call:



login = async (loginProps) => {
try {
let api = axios.create({
baseURL: 'http://localhost/5001',
timeout: 100000
});

return await api.post(`/api/login`, loginProps);
} catch (error) {
debugger;
throw error;
}
}






node.js reactjs cors axios






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 3 at 5:12







user1790300

















asked Jan 3 at 4:20









user1790300user1790300

42611355




42611355













  • stackoverflow.com/questions/18642828/…

    – Vishal-Lia
    Jan 3 at 4:32











  • Why would an exception be caught and the error object, the parameter of the catch condition be undefined?

    – user1790300
    Jan 3 at 16:09



















  • stackoverflow.com/questions/18642828/…

    – Vishal-Lia
    Jan 3 at 4:32











  • Why would an exception be caught and the error object, the parameter of the catch condition be undefined?

    – user1790300
    Jan 3 at 16:09

















stackoverflow.com/questions/18642828/…

– Vishal-Lia
Jan 3 at 4:32





stackoverflow.com/questions/18642828/…

– Vishal-Lia
Jan 3 at 4:32













Why would an exception be caught and the error object, the parameter of the catch condition be undefined?

– user1790300
Jan 3 at 16:09





Why would an exception be caught and the error object, the parameter of the catch condition be undefined?

– user1790300
Jan 3 at 16:09












2 Answers
2






active

oldest

votes


















1














You can either set the request header (cross origin) by yourself or use the CORS package (npm i cors --save)



without using cors package ->



app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
if (req.method === 'OPTIONS') {
var headers = {};
// headers["Access-Control-Allow-Origin"] = req.headers.origin;
headers["Access-Control-Allow-Origin"] = "*";
headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE,
OPTIONS";
headers["Access-Control-Allow-Credentials"] = false;
headers["Access-Control-Max-Age"] = '86400'; // 24 hours
res.writeHead(200, headers);
res.end();
} else {
next();
}
});


If you are using cors (npm i cors --save)



const cors = require('cors')
app.use(cors());



for more cors package configuration, just refer https://github.com/expressjs/cors






share|improve this answer































    0














    The server that is receiving the request must set CORS headers to let the browser know the server is expecting requests outside of it's domain. You can always set them manually, but if you are using express there is a library that does that easily - https://expressjs.com/en/resources/middleware/cors.html. Most popular node frameworks should have an equivalent.






    share|improve this answer
























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54016292%2freceiving-cors-error-while-running-two-servers-on-localhost%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      You can either set the request header (cross origin) by yourself or use the CORS package (npm i cors --save)



      without using cors package ->



      app.use((req, res, next) => {
      res.header('Access-Control-Allow-Origin', '*');
      if (req.method === 'OPTIONS') {
      var headers = {};
      // headers["Access-Control-Allow-Origin"] = req.headers.origin;
      headers["Access-Control-Allow-Origin"] = "*";
      headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE,
      OPTIONS";
      headers["Access-Control-Allow-Credentials"] = false;
      headers["Access-Control-Max-Age"] = '86400'; // 24 hours
      res.writeHead(200, headers);
      res.end();
      } else {
      next();
      }
      });


      If you are using cors (npm i cors --save)



      const cors = require('cors')
      app.use(cors());



      for more cors package configuration, just refer https://github.com/expressjs/cors






      share|improve this answer




























        1














        You can either set the request header (cross origin) by yourself or use the CORS package (npm i cors --save)



        without using cors package ->



        app.use((req, res, next) => {
        res.header('Access-Control-Allow-Origin', '*');
        if (req.method === 'OPTIONS') {
        var headers = {};
        // headers["Access-Control-Allow-Origin"] = req.headers.origin;
        headers["Access-Control-Allow-Origin"] = "*";
        headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE,
        OPTIONS";
        headers["Access-Control-Allow-Credentials"] = false;
        headers["Access-Control-Max-Age"] = '86400'; // 24 hours
        res.writeHead(200, headers);
        res.end();
        } else {
        next();
        }
        });


        If you are using cors (npm i cors --save)



        const cors = require('cors')
        app.use(cors());



        for more cors package configuration, just refer https://github.com/expressjs/cors






        share|improve this answer


























          1












          1








          1







          You can either set the request header (cross origin) by yourself or use the CORS package (npm i cors --save)



          without using cors package ->



          app.use((req, res, next) => {
          res.header('Access-Control-Allow-Origin', '*');
          if (req.method === 'OPTIONS') {
          var headers = {};
          // headers["Access-Control-Allow-Origin"] = req.headers.origin;
          headers["Access-Control-Allow-Origin"] = "*";
          headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE,
          OPTIONS";
          headers["Access-Control-Allow-Credentials"] = false;
          headers["Access-Control-Max-Age"] = '86400'; // 24 hours
          res.writeHead(200, headers);
          res.end();
          } else {
          next();
          }
          });


          If you are using cors (npm i cors --save)



          const cors = require('cors')
          app.use(cors());



          for more cors package configuration, just refer https://github.com/expressjs/cors






          share|improve this answer













          You can either set the request header (cross origin) by yourself or use the CORS package (npm i cors --save)



          without using cors package ->



          app.use((req, res, next) => {
          res.header('Access-Control-Allow-Origin', '*');
          if (req.method === 'OPTIONS') {
          var headers = {};
          // headers["Access-Control-Allow-Origin"] = req.headers.origin;
          headers["Access-Control-Allow-Origin"] = "*";
          headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE,
          OPTIONS";
          headers["Access-Control-Allow-Credentials"] = false;
          headers["Access-Control-Max-Age"] = '86400'; // 24 hours
          res.writeHead(200, headers);
          res.end();
          } else {
          next();
          }
          });


          If you are using cors (npm i cors --save)



          const cors = require('cors')
          app.use(cors());



          for more cors package configuration, just refer https://github.com/expressjs/cors







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jan 3 at 5:12









          Mr.BhatMr.Bhat

          12410




          12410

























              0














              The server that is receiving the request must set CORS headers to let the browser know the server is expecting requests outside of it's domain. You can always set them manually, but if you are using express there is a library that does that easily - https://expressjs.com/en/resources/middleware/cors.html. Most popular node frameworks should have an equivalent.






              share|improve this answer




























                0














                The server that is receiving the request must set CORS headers to let the browser know the server is expecting requests outside of it's domain. You can always set them manually, but if you are using express there is a library that does that easily - https://expressjs.com/en/resources/middleware/cors.html. Most popular node frameworks should have an equivalent.






                share|improve this answer


























                  0












                  0








                  0







                  The server that is receiving the request must set CORS headers to let the browser know the server is expecting requests outside of it's domain. You can always set them manually, but if you are using express there is a library that does that easily - https://expressjs.com/en/resources/middleware/cors.html. Most popular node frameworks should have an equivalent.






                  share|improve this answer













                  The server that is receiving the request must set CORS headers to let the browser know the server is expecting requests outside of it's domain. You can always set them manually, but if you are using express there is a library that does that easily - https://expressjs.com/en/resources/middleware/cors.html. Most popular node frameworks should have an equivalent.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 3 at 4:35









                  TylerTyler

                  20933




                  20933






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54016292%2freceiving-cors-error-while-running-two-servers-on-localhost%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      MongoDB - Not Authorized To Execute Command

                      How to fix TextFormField cause rebuild widget in Flutter

                      in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith