-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
  • 15,447
  • 5
  • 79
  • 98
Andrew Lee
  • 19
  • 3

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();
  });