如何获取我的 API 请求以获取更新的数据库?
Posted
技术标签:
【中文标题】如何获取我的 API 请求以获取更新的数据库?【英文标题】:How do I get my API request to grab the updated Database? 【发布时间】:2020-01-17 20:17:48 【问题描述】:第一次,所以提前谢谢。
我试图让当我更改我的“数据库”(我将在下面解释引用)时,API 请求也会自动更新。目前,当我更改“数据库”时,API 请求仍然只是检索旧数据。
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`));
所以这将是我的“数据库”。
然后使用 clickHandler,我正在请求名称。
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;
目前,单击该按钮会正确填充“我的锻炼计划 - 更新”,但如果我在我的 const 锻炼计划中将其更改为“我的锻炼计划 - 无更新”,单击该按钮仍会检索“我的锻炼计划 -更新”。
让我知道我可以做些什么来帮助使这更清晰/更容易!
【问题讨论】:
【参考方案1】:每次对服务器进行更改时,都需要重新启动 express 应用程序。在您这样做之前,服务器仍在为旧常量提供服务。
在开发过程中,您可能需要考虑options to make this automatic。我过去使用过nodemon 并取得了一些成功。我相信还有很多其他选择。
【讨论】:
【参考方案2】:我认为您从 url 获得了缓存内容。您可以尝试在 url 中添加附加随机查询或添加 header 'Cache-Control': 'no-cache' 以防止缓存数据。 考试:/api/workout-plan?random=12312312。
【讨论】:
这似乎是一个很长的镜头......我不确定我是否希望浏览器在没有服务器首先发送缓存标头的情况下缓存它。以上是关于如何获取我的 API 请求以获取更新的数据库?的主要内容,如果未能解决你的问题,请参考以下文章
使用来自网站 API 的 POST 请求获取 Json 数据 [重复]
“不支持的获取请求” - 页面的 Facebook 实时更新