简体   繁体   English

无法使用 React 客户端发出 API 请求

[英]Can't make an API request with React client

I'm trying to make my react app reference a mongoDB database, but I'm having some serious issues with the request.我试图让我的 React 应用程序引用 mongoDB 数据库,但我遇到了一些严重的请求问题。

Here's the Service in the client.这是客户端中的服务。

import axios from "axios";

export default
{
    getAll: async () => {
        axios.get("api/quizlist").then((res) => {
            return res;
        }).catch(err =>
            {
                console.log(err);
            });
    }
}

Here's the Route I'm trying to call:这是我要拨打的路线:

app.get("/api/quizlist", (req,res) => {
  console.log("Recieved Request");
  db.QuizData.find().then(data => {
    console.log("Passed Data");
    res.json(data);
  }).catch(err => {
    res.json(err);
  });
});

The error message I'm getting is我收到的错误信息是

Error: Request failed with status code 504
    createError createError.js:16
    settle settle.js:17
    handleLoad xhr.js:61

I've tried to set up a proxy connection with this in the API:我试图在 API 中与此建立代理连接:

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "server": "nodemon server.js"
  }

and this in the client:这在客户端:

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "proxy": "http://localhost:5000"
  }

(The API is connecting to port 5000) (API 连接到端口 5000)

The proxy doesn't belong in the scripts object in the package.json file move it out like this proxy不属于package.json文件中的脚本 object 像这样将其移出

"proxy": "http://localhost:5000"
"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
}

(you need to restart your app after making changes in the package.json file) (修改package.json文件后需要重启应用)

You are also missing a / in your front end request您的前端请求中还缺少/

Change改变

import axios from "axios";

export default
    {
        getAll: async () => {
            
            // change
            axios.get("api/quizlist").then((res) => {

            // to
            axios.get("/api/quizlist").then((res) => {

            return res;
        }).catch(err =>
        {
            console.log(err);
        });
    }
}

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

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