【发布时间】: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