简体   繁体   中英

How do I get my API request to grab the updated Database?

1st time everything, so thanks in advance.

I'm trying to get is so that when I change my "database" (I'll explain the quotations down below), the API request also auto updates. Currently, when I change the "database", the API request is still only retrieving the old data.

const express = require("express");
const app = express();

const workoutPlan = {
  ID: 1,
  Name: "My Workout Plan - Update"
};

app.get("/api/workout-plan", function(req, res) {
  res.json(workoutPlan);
});

app.listen(3001, () => console.log(`Server listening on port 3001`));

So this would be my "database".

Then using a clickHandler, I'm requesting for the Name.

import React from "react";
import Workout from "./Workout";
import axios from "axios";

class WorkoutPlan extends React.Component {
  constructor() {
    super();
    this.state = {
      workoutPlan: {}
    };

    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    axios
      .get("/api/workout-plan")
      .then(response => this.setState({ workoutPlan: response.data }));
  } 



  render() {
    const { workoutPlan } = this.state;
    // const workoutPlan = this.state.workoutPlan;

    return (
      <div>
        <h1>{workoutPlan.Name}</h1>
        <button className="button" onClick={this.handleClick}>
          Click Me
        </button>
        <Workout />
      </div>
    );
  }
}

export default WorkoutPlan;

At the moment, clicking the button, properly populates "My Workout Plan - Update", but if I change that in my const workoutPlan to "My Workout Plan - No Update", clicking that button still retrieves "My Workout Plan - Update".

Let me know what I can do to help makes this clearer/easier!

I think you have got a cached content from url. U can try add append random query or add header { 'Cache-Control': 'no-cache' } in url to prevent cached data. Exam: /api/workout-plan?random=12312312.

You need to restart the express application each time you make changes to the server. Until you do that, the server is still serving the old constants.

During development, you might want to consider options to make this automatic . I've used nodemon in the past with some success. I'm sure there are plenty of other options too.

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