简体   繁体   English

使用 Axios 从快递服务器请求数据的问题

[英]Problem to request data from express server with Axios

I have an application in react on my domain with a server in Express.The project is divided into two sections (folders), "Frontend" and "Backend".我有一个应用程序在我的域上与 Express 中的服务器做出反应。该项目分为两个部分(文件夹),“前端”和“后端”。 When I start the express server it listens on port 4000, but when the application in React makes the request with axios through the path Ex:(" https://localhost.com/dataRequested ") get the 404 error.当我启动 express 服务器时,它会在端口 4000 上进行侦听,但是当 React 中的应用程序通过路径 Ex:(" https://localhost.com/dataRequested ") 使用 axios 发出请求时,会出现 404 错误。 When I add the port to the domain of the listening server, the request work.当我将端口添加到侦听服务器的域时,请求工作。 Ex:(" https://localhost.com:4000/dataRequested ")例如:(“ https://localhost.com:4000/dataRequested ”)

Index.js server Express 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 route server Express handler.js 路由服务器 Express

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

hero.js component React app hero.js 组件 React 应用

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

Probably CORS issue if the react app is stand alone..如果反应应用程序是独立的,则可能是 CORS 问题..

try adding this to express app尝试将此添加到快递应用程序

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

Add this to your package.json file将此添加到您的 package.json 文件中

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

this is used by react to send all fetch/axios requests to the node server (only in development). react 使用它来将所有 fetch/axios 请求发送到节点服务器(仅在开发中)。 Then the node server should know whether to forward that request to the Reactjs router or to the express router然后节点服务器应该知道是将该请求转发到 Reactjs 路由器还是快速路由器

I add "/api" before all of my API calls to help express figure out which router to use我在所有 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'));
});

and now your axios call will look like现在你的 axios 调用看起来像

axios.get('/api/randomElementsData')

Try hitting the endpoint http://localhost:4000/dataRequested尝试点击端点http://localhost:4000/dataRequested

This may even be because of URL being Invalid这甚至可能是因为 URL 无效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM