node.js - 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);
解决方案
尝试制定 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();
});
推荐阅读
- php - 如何跨多个 Symfony 项目同步数据库中的内容?
- java - 如何找到 html-table ID
- excel - 当同一行中的单元格更改为应用于多行时,清除该行中的单元格内容
- c - C将char转换为字符串
- asp.net-core - 无法启动传输“WebSockets”
- php - Foreach 循环只打印一个名称而不是几个
- react-native - 如何在 React Native 中获取屏幕尺寸
- javascript - 快速文件上传和查看
- laravel - 查询生成器表中的 SUM() 语法错误或访问冲突
- kubernetes - 无法在 GCP 上部署 Kubeflow:告诉我启用已启用的 API