Node.js 使用React前端设置Express后端
所以基本上我知道它非常简单,但是我在设置前端和后端逻辑对话时遇到了麻烦。我只是想从express中获取数据,以了解它的工作情况,但我甚至似乎无法做到这一点 我还在前端使用Next.js,这对我来说也是新的 无论如何,这里是我试图获取到后端的页面 我得到一个未定义的无法设置属性“state”Node.js 使用React前端设置Express后端,node.js,reactjs,express,next.js,Node.js,Reactjs,Express,Next.js,所以基本上我知道它非常简单,但是我在设置前端和后端逻辑对话时遇到了麻烦。我只是想从express中获取数据,以了解它的工作情况,但我甚至似乎无法做到这一点 我还在前端使用Next.js,这对我来说也是新的 无论如何,这里是我试图获取到后端的页面 我得到一个未定义的无法设置属性“state” import React from "react"; import styled from "styled-components"; import axios from 'axios'; const T
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;
下面是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;
您使用的是功能组件,它没有
此
上下文。您必须将useState
与下面的函数组件一起使用
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>
)
}
const TestApi=(道具)=>{
const[testApi,setTestApi]=React.useState(“”);
取('http://localhost:3001/users', {
方法:“获取”
})
.then(response=>response.text())
.then(response=>setTestApi(response))
//response.json().then(body=>{
//此.setState({TestApi:`http://localhost:3001/users${body.body}`})
// })
返回(
{testApi}
)
}
是的,我让它工作起来了,不得不稍微重构fetch。
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>
)
}