表达如何通过不同的端点重定向json数据

问题描述 投票:0回答:1

我对使用express很陌生,而StackOverflow上的响应非常令人困惑。我所拥有的是我使用app.get()检索的JSON数据。我想要的是修改此数据并将其发送到我的index.html文件。我知道我可以简单地使用fetch函数从get端点获取索引文件中的数据,但是我需要同时使用app.post()和app.put()函数。

javascript express
1个回答
0
投票

我无法理解您的问题。

这里是一个示例代码,该示例代码使用axios和普通的javascript来从后端获取一些数据,然后在前端中,您可以修改数据。您可以替换axios进行获取,并且仍然可以使用。

app.js

const express = require("express");
const bodyParser = require("body-parser");
const port = 8000;

const app = express();

/* Simulating data, a better approach would be to use some storage like MySQL... */
let data = {
    name: "Elon Musk",
    age: "48",
    height: "1.88m"
};

app.use(express.static("public"));
/* body-parser is required so the server can parse the data sent. */
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

/* get the data... */
app.get("/api/mydata", function(req, res) {
    return res.json(data);
});

/* this is where the client will post the data */
app.post("/api/newdata", function(req, res) {
    data.name = req.body.name;
    data.age = req.body.age;
    return res.json("OK!");
});

app.listen(port, function() {
    console.log("Listening on 8000");
});

public / index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

    <input type="text" id="name" placeholder="Name..." value="">
    <input type="text" id="age" placeholder="Age..." value="">

    <button type="button" id="setValues">Change values!</button>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.js"></script>
    <script>
        window.addEventListener("load", function() {
            axios.get("/api/mydata").then(function(res) {
                document.getElementById("name").value = res.data.name;
                document.getElementById("age").value = res.data.age;
            })
        });

        document.getElementById("setValues").addEventListener("click", function() {
            axios.post("/api/newdata", { 
                name: document.getElementById("name").value,
                age: document.getElementById("age").value
            }).then(function(res) {
                console.log("Sent!");
            })
        })
    </script>
</body>
</html>

如果有任何疑问,请告诉我!

© www.soinside.com 2019 - 2024. All rights reserved.