【问题标题】:Problem to request data from express server with Axios使用 Axios 从 express 服务器请求数据的问题
【发布时间】:2022-01-06 20:32:17
【问题描述】:

我有一个应用程序在我的域上与 Express 中的服务器做出反应。该项目分为两个部分(文件夹),“前端”和“后端”。当我启动 express 服务器时,它会在端口 4000 上进行侦听,但是当 React 中的应用程序通过路径 Ex:("https://localhost.com/dataRequested") 使用 axios 发出请求时,会出现 404 错误。当我将端口添加到侦听服务器的域时,请求工作。例如:("https://localhost.com:4000/dataRequested")

Index.js 服务器快递

const routesHandler = require('./routes/handler.js');
const bodyParser = require('body-parser');
const https = require('https');
const fs = require('fs');
var privateKey  = fs.readFileSync('sslcert/server.key', 'utf8');
var certificate = fs.readFileSync('sslcert/server.crt', 'utf8');

const credentials = {key: privateKey, cert: certificate};
const express = require('express');

const app = express();
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use('/', routesHandler);

const httpsServer = https.createServer(credentials, app);

httpsServer.listen(4000);

handler.js 路由服务器 Express

router.get('/randomElementsData', (req, res) =>
{
  //functions
}

hero.js 组件 React 应用

const getHeroData = async () =>
{
   try
   {
      const response = await axios.get('/randomElementsData');
      setDataHero(response);
   }
   catch (error)
   {
      console.log(error);
   }
}

【问题讨论】:

  • 你在 package.json 中添加代理了吗? "代理": "localhost:4000"
  • 因为当您将端口添加到 API 调用时它可以工作...我会说您需要添加代理

标签: node.js reactjs express


【解决方案1】:

将此添加到您的 package.json 文件中

"proxy" : "http://localhost:4000"

react 使用它来将所有 fetch/axios 请求发送到节点服务器(仅在开发中)。然后节点服务器应该知道是将该请求转发到 Reactjs 路由器还是快速路由器

我在所有 API 调用之前添加“/api”,以帮助确定要使用哪个路由器

app.use('/api', routesHandler);

// All other GET requests not handled before will return our React app

app.get("/*", (req, res) => {
  res.sendFile(<the location of your build folder>);
// res.sendFile(path.join(__dirname, '/build'));
});

现在你的 axios 调用看起来像

axios.get('/api/randomElementsData')

你的 Nginx 反向代理应该是这样的

   location / {
        proxy_pass http://localhost:4000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

【讨论】:

  • 是的,这适用于开发级别,但现在 React 中的应用程序是一个构建,并且“package.json”文件不存在。我也尝试在构建中上传文件,但结果不一样
  • 我编辑了我的答案...看看有没有帮助你
  • 我已经更新了代码,但没有任何改变。 4000 端口不监听请求
  • @Garw 你在哪里托管 React 应用程序和 NodeJS 服务器?它们都在同一台服务器上吗?
  • 它们都在同一个服务器和我域的同一个“public_html”文件夹中。
【解决方案2】:

如果反应应用是独立的,可能是 CORS 问题..

尝试将其添加到快递应用中

  app.use((req, res, next) => {
      res.header('Access-Control-Allow-Origin', `http://${process.env.HOST}:${process.env.PORT_CLIENT}`) // update to match the domain you will make the request from
      res.header('Access-Control-Allow-Credentials', true)
      res.header(
        'Access-Control-Allow-Headers',
        'Origin, X-Requested-With, Content-Type, Accept, Authorization, X-Auth-Token'
      )
      res.header('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS,POST,PUT')
      if (req.method === 'OPTIONS') {
        res.status(204).send()
      } else {
        next()
      }
    })

【讨论】:

  • 我添加了代码,但没有任何改变
  • 如果它在同一个域上,不要认为你需要 cors
  • 你有任何console.errors吗?
【解决方案3】:

尝试到达终点 http://localhost:4000/dataRequested

这甚至可能是因为 URL 无效

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-18
    • 2021-06-05
    • 2016-09-13
    • 1970-01-01
    • 2020-02-13
    • 2022-11-17
    • 1970-01-01
    • 2020-06-26
    相关资源
    最近更新 更多