Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/magento/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何在React中使用axios解决get请求?_Reactjs_Axios - Fatal编程技术网

Reactjs 如何在React中使用axios解决get请求?

Reactjs 如何在React中使用axios解决get请求?,reactjs,axios,Reactjs,Axios,我是Axios的新手,我试图从端点获取数据以用于React import axios from "axios"; const api = axios.create({ baseURL: "http://localhost:5000/" }); export default function App() { api.get("/products").then(res => console.log(res.data));

我是Axios的新手,我试图从端点获取数据以用于React

import axios from "axios";

const api = axios.create({ baseURL: "http://localhost:5000/" });

export default function App() {
  api.get("/products").then(res => console.log(res.data));
  ...
}
这是我的端点代码

const express = require("express");
const app = express();

require("dotenv").config();

app.get("/products", (req, res) => {
  res.send("Hello world!");
});

const port = process.env.PORT;
app.listen(port, () => console.log(`Listening on port ${port}...`));
而不是
你好,世界正在记录我收到此错误

任何帮助都将不胜感激。

您好,请查找此express库,您可以在package.json中的react项目中使用proxy,而不是axios.create() 像


在后端服务器中安装
cors
中间件

  • npm安装cors
  • 启用所有CORS请求
  • 您可以查找更多信息。还有一些方法可以配置CORS

    对于您的另一个问题,CRUD操作应该在
    useffect
    hook中使用

    import React, { useEffect } from 'react';
    
    export default function App() {
    
      useEffect(() => {
    
        api.get("/products").then(res => console.log(res.data));
    
      }, [])
    
      ...
    }
    

    谢谢你的回复。但是我要接受另一个答案,因为它告诉我如何设置cors。但是你能提供为什么我的代码不起作用以及cors是什么吗?另外hello world被记录了两次。@Ethanal你必须使用
    useEffect
    hook才能产生任何副作用。也就是说,任何CURD请求都应该放在useffect挂钩中,这样就不会有重新渲染效果。我将编辑我的答案以反映
    useffect
    hook的用法。
    const express = require("express");
    var cors = require('cors')
    const app = express();
    
    app.use(cors())
    
    import React, { useEffect } from 'react';
    
    export default function App() {
    
      useEffect(() => {
    
        api.get("/products").then(res => console.log(res.data));
    
      }, [])
    
      ...
    }