【问题标题】:Express Server to bypass CORS [closed]Express Server 绕过 CORS [关闭]
【发布时间】:2019-08-31 21:21:48
【问题描述】:

我正在尝试解决客户端的 CORS 问题。服务器端工作正常,没有任何问题,但未启用 CORS。我使用 React 构建了一个页面应用程序。我正在使用节点 Js 和 express 编写一个非常简单的代理服务器,它将所有传入请求的路径以“/api”开头的路径转发到“https://api.example.com”。我已经使用请求库来实现这一点,并且在使用邮递员进行测试时,一切都按预期工作。但是当我从 React 前端尝试时;我收到了这个错误:500 Internal Server error。请问我做错了什么?我不能只是围绕这个问题。您的帮助将不胜感激...这是 server.js:

const express  = require('express');
const path     = require('path');
const request  = require('request');

//create express app instance
const app = express();

//set the port as env variable
const PORT    = process.env.PORT || 3030;
const API_URL = 'https://api.example.com';

//This will pipe the whole request to the API endpoint
//and pipe the response back to the requester.
app.use('/api', function(req, res) {
  req.pipe(request(`${API_URL}${req.url}`)).pipe(res);
});


if (process.env.NODE_ENV === 'production') {
  // Serve any static files
  app.use(express.static(path.join(__dirname, '../build')));
  // Handle React routing, return all requests to React app
  app.get('*', function(req, res) {
    res.sendFile(path.join(__dirname, '../build', 'index.html'));
  });
}

//The server will now listen on the provided port
app.listen(PORT, () => console.log(`Listening on port ${PORT}...`));

【问题讨论】:

  • `500 Internal Server error`与CORS无关。检查后端的日志。

标签: javascript node.js express ecmascript-6


【解决方案1】:

安装 cors 库 npm install cors --save 并像这样使用它。

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

/**use dependencies*/

app.use(cors());

【讨论】:

  • 我已经绕过了请求库。 500内部错误很奇怪,因为服务器端工作正常。
猜你喜欢
  • 2020-08-09
  • 2019-06-26
  • 2021-11-04
  • 2021-06-09
  • 1970-01-01
  • 1970-01-01
  • 2019-11-27
  • 2020-05-05
  • 2022-01-14
相关资源
最近更新 更多