javascript - 使用 express 发送和接收数据
问题描述
我有一个正在运行的快速服务器,它从我的项目的公共文件夹中发送一个 html 文件。它来自一个从这个html文件链接的客户端脚本,我试图请求并将数据发送到服务器。我几乎到处都看过,但没有找到一种方法来做到这一点。我认为可以只使用 express 来完成,但我似乎无法弄清楚。我觉得我一定是遗漏或误解了一些明显的东西。我怎样才能做到这一点?
|--index.js
|--template.json
|--public
| |--index.html
| |--client.js
1:这是我的文件结构。我试图让 client.js 向 index.js 发送一个请求,然后它会以一些 json 响应。
任何解决方案甚至只是指针都值得赞赏。
解决方案
这是一个简单的设置:
1) Expressindex.html
从public/
执行的文件夹中提供服务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"}
参考:
推荐阅读
- ios - 将最小部署目标升级到 iOS 14 后 UICollectionView 停止显示单元格
- r - 谷歌翻译按钮 R 闪亮
- python - How to find out what's the hash added to POST method
- markdown - 如何将包含图像的降价文件发送到另一台计算机?
- spring - 如何以编程方式评估注释中使用的表达式(拼写/变量引用)?
- java - 双击表格行并在输入字段中插入值
- angular - getOrgChart 库(版本 - 2.5.3)中面临问题,字段存在于数据源中,但在渲染节点函数 args.node.data 中缺失
- r - 如何重写循环以在 R 中运行得更快?
- c++ - 使用 minHeap 构建优先级队列
- time-series - 我可以计算包含某个值的 Prophet 模型的置信区间吗?