-1

When I create two servers using Nodejs with http and both have express as request handler, one is running at localhost:3000, which is used for handling api. And the other at localhost:5000 and I try to fetch the api from localhost:3000, I expect to get a cors error, but surprisingly I can fetch it with no error. I wonder why, is it because of express?

The localhost:5000 code

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

const axios = require('axios');

const http = require('http');
const server = http.createServer(app);

app.get('/', async (req, res) => {
 try {
    const response = await axios.get('http://localhost:3000/users');
    console.log(typeof response.data);
    res.send(response.data[1]);
} catch(err) {
    console.error(err);
  }
});

server.listen(5000);
Penny Liu
  • 11,885
  • 5
  • 66
  • 81
Andrew Lee
  • 13
  • 2
  • 1
    I'm not sure I understand--you're not making an XHR request. – Dave Newton Apr 17 '20 at 14:46
  • They are on same machine. – cybercoder Apr 17 '20 at 14:49
  • You have created a proxy server, you aren't making and CORS requests. CORS requests happen when a user is on `somedomain.biz` and the site tries to make a request to `someotherdomain.org`. It's something that happens purely client side. – zero298 Apr 17 '20 at 14:54

1 Answers1

-2

try putting cors rules,

app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
    res.setHeader('Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
  });