首页 > 解决方案 > 使用 express 发送和接收数据

问题描述

我有一个正在运行的快速服务器,它从我的项目的公共文件夹中发送一个 html 文件。它来自一个从这个html文件链接的客户端脚本,我试图请求并将数据发送到服务器。我几乎到处都看过,但没有找到一种方法来做到这一点。我认为可以只使用 express 来完成,但我似乎无法弄清楚。我觉得我一定是遗漏或误解了一些明显的东西。我怎样才能做到这一点?

|--index.js
|--template.json
|--public
|  |--index.html
|  |--client.js

1:这是我的文件结构。我试图让 client.js 向 index.js 发送一个请求,然后它会以一些 json 响应。


任何解决方案甚至只是指针都值得赞赏。

标签: javascriptnode.jsexpress

解决方案


这是一个简单的设置:

1) Expressindex.htmlpublic/执行的文件夹中提供服务client.js

2) 我们有一个 Express 路由,它读取template.json文件并将其加载到位于/json/

3) 通过client.js执行 Ajax 请求fetch(),命中/json/路由,该路由将 JSON 内容提供给浏览器脚本

index.js

const express = require("express");
const app = express();
const data = require("./template.json");

app.use( express.static( __dirname + '/public' ) );

app.get("/json", (req,res)=>{
    // Send a JSON response with the data from template.json
    res.json( data );
})

app.listen( 8080 );

索引.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>Express</title>
</head>
<body>
    <h1>Express</h1>
    <script src="client.js"></script>
</body>
</html>

客户端.js

// Make an HTTP request to the /json/ route of our express server:
fetch("/json")
// Get the request body and convert to JSON:
.then((res)=> res.json())
// Here we have the request body as a JSON object ready to be used:
.then((data)=>{

    console.log( data );

})
.catch(console.error);

模板.json

{"firstname":"john","lastname":"doe"}

参考:


推荐阅读