3

I'm setting up a local backend server with node, and I'm trying use fetch to get values to render in my frontend react app. I've gotten most of the way, as everything compiles, however I'm running into issues with fetching the correct values. Or at least, I think I'm doing everything correctly.

The goal is to use fetch() in my app.js to get render values from route foo in server.js.

I can get a response from /foo but it is not what I was sending. I was sending a json object {text: "Foo"}

However, I'm receiving this in the console: App.js:12 Response {type: "basic", url: "http://localhost:3000/foo", redirected: false, status: 200, ok: true, …}

Any idea what I'm doing wrong?

Am I not fetching or sending objects correctly between routes? How can I get "Foo" to render on the line <p>The current state is {this.state.message}</p> in 'App.js`

Here is my app.js:

import React, {Component} from 'react';
import './App.css';

class App extends Component {
    state = {
        message: ""
    };

    componentDidMount() {
        fetch('/foo')
            .then(res => {
                console.log(res);
                return res.json();
                // .then(express => this.setState({ express }))
                // .then(() => console.log(this.state.message));
            });
    }

    render() {
        return (
            <div className="App">
                <h1>Users</h1>
                <p>The current state is {this.state.message}</p>
            </div>
        );
    }
}

export default App;

Here is my server.js:

const express = require('express');
const users = require('./routes/users');
const foo = require('./routes/foo');

const app = express();
const port = process.env.PORT || 8080;

// Set a route for when commands are processed for users
app.use('/users', users);
app.use('/foo', foo);

app.get('/api/hello', (req, res) => {
    res.send({ express: 'Hello From Express' });
});

app.listen(port, () => console.log(`Listening on port ${port}`));

Here is my foo.js

let express = require('express');
let router = express.Router();

router.get('/', function(req, res) {
    res.send([{text: "Foo"}]);
});

router.post('/', function(req, res) {
    res.send('POST handler for /foo route.');
});

module.exports = router;

1 Answer 1

1

the res.json() is still returning a promise, try this out:

  componentDidMount() {
    fetch("/foo").then(res =>
      res.json().then(data => {
        console.log("data", JSON.stringify(data, null, 4));
        // here you can set state
        //...
      })
    );
  }
Sign up to request clarification or add additional context in comments.

1 Comment

That was it. Thanks for seeing that :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.