首页 > 解决方案 > CORS error not showing when using express

问题描述

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

标签: node.jsexpresscors

解决方案


尝试制定 cors 规则,

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


推荐阅读