【问题标题】:How to get api data from nodejs app to appear on react frontend with axios如何从nodejs应用程序获取api数据以显示在带有axios的反应前端
【发布时间】:2021-09-07 12:17:24
【问题描述】:

从我的前端,我试图从运行在端口 5000 的后端获取数据。我不确定该端口是否应该在运行 react 应用程序之前运行。但是,我尝试了这两种情况,我在不同的终端上运行后端端口 5000,然后在不同的终端上运行前端。我实际上是否使用带有 axios 的 get 方法的请求或响应?请问,我的代码有什么问题吗?

这是我的前端

import React, {useState} from 'react';
import axios from "axios";

const Quotes = () => {
    const [text, setText] = useState("");
    const [author, setAuthor] = useState("");
function getQuote(){
    axios.get("https://localhost:5000/", { crossdomain: true }).then(response => {
    setText(response.data.text);
    setAuthor(response.data.author);
});
}
    return (
        <div>
            <button onClick={getQuote}> Generate Quote</button>
            <h1>{text}</h1>
            <h3>{"-" + author}</h3>
        </div>
    )
}

export default Quotes;

所以,在这里,我正在尝试将 API 数据通过 express 发送到主页。而且我很难理解为什么它没有出现在前端。

这是我的后台

const express = require("express");
const quote = require('inspirational-quotes');

const app = express();

app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    next();
  });

app.get("/", function(req, res){ // quotes is send to the homepage of app
    res.send(quote.getQuote());
});

let port = process.env.PORT;
if (port == null || port == ""){
    port = 5000;
}
app.listen(port, () =>{
    console.log("Server is running...");
});

当我在端口 5000 上运行后端时,我得到了数据,但我没有让它显示在 react 应用程序上。请帮忙。

【问题讨论】:

    标签: node.js reactjs express axios


    【解决方案1】:

    我解决了我的错误。我不得不从浏览器控制台调试它。我意识到我使用https 作为本地主机。这是错误的 URL 协议。

    我通过将 https://localhost:5000/ 更改为 http://localhost:5000/ 来纠正它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-09
      • 2017-07-24
      • 2020-03-16
      • 1970-01-01
      • 1970-01-01
      • 2020-06-28
      • 2019-11-27
      • 2021-07-26
      相关资源
      最近更新 更多