简体   繁体   中英

Setting up a Express backend with React Front-end

So basically I know its super simple but I am having trouble setting up my frontend talking to my backend logic. I am just trying to grab the data from express just to know its working, and I can't even seem to do that.

I am also using Next.js in the front-end which is new to me as well.

Anyways here is the page where I am trying to fetch to the backend..

I am getting a Cannot set property 'state' of undefined

  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;

And here is my back-end code and hosted on port 3001. route: 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;

and here is the 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;

You are using functional components, and it doesn't have this context. You have to use useState with function componoents like below.

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>
    )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM