[英]Setting up a Express backend with React Front-end
所以基本上我知道它超級簡單,但是我在設置前端與后端邏輯對話時遇到了麻煩。 我只是想從 express 中獲取數據只是為了知道它的工作原理,我什至似乎都做不到。
我還在前端使用 Next.js,這對我來說也是新的。
無論如何,這里是我試圖獲取到后端的頁面..
我得到一個無法設置未定義的屬性“狀態”
import React from "react";
import styled from "styled-components";
import axios from 'axios';
const TestApi = (props) => {
this.state = {
TestApi: ''
}
fetch('http://localhost:3001/users', {
method: 'GET'
})
.then(response => response.text())
.then(response => this.setState({ TestApi: response }))
// response.json().then(body => {
// this.setState({ TestApi: `http://localhost:3001/users${body.body}` })
// })
return (
<p>{this.state.TestApi}</p>
)
}
export default TestApi;
這是我的后端代碼,托管在端口 3001 上。路由:users.js
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function (req, res, next) {
res.text('respond with a resource');
});
module.exports = router;
這是 app.js
const express = require("express");
const app = express();
const cors = require("cors");
const bodyParser = require("body-parser");
const logger = require("morgan");
// const port = process.env.PORT || 3001;
app.use(logger('dev'));
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
const usersRouter = require("./routes/users");
app.use("/users", usersRouter);
module.exports = app;
您正在使用功能組件,它沒有this
上下文。 您必須將useState
與 function 組件一起使用,如下所示。
const TestApi = (props) => {
const [testApi, setTestApi] = React.useState('');
fetch('http://localhost:3001/users', {
method: 'GET'
})
.then(response => response.text())
.then(response => setTestApi(response))
// response.json().then(body => {
// this.setState({ TestApi: `http://localhost:3001/users${body.body}` })
// })
return (
<p>{testApi}</p>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.