javascript - 使用 Express 发送和接收数据

标签 javascript node.js express

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

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

1: Here is my file structure. I am trying to have client.js send a request to index.js which then will respond with some json.


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

最佳答案

这是一个简单的设置:

1) Express 从执行 client.jspublic/ 文件夹中提供 index.html

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

的路由中

3) client.js 通过 fetch() 执行 Ajax 请求,点击 /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 );

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

client.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"}

引用文献:

关于javascript - 使用 Express 发送和接收数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58349558/

相关文章:

android - NativeScript 安装错误 - npm Fiber

node.js - 使用 express 服务 svg 文件

javascript - 删除li对动态li不起作用

javascript - 循环数组与循环对象的速度

Javascript 获取事件处理程序不起作用

javascript - 使用 MEAN Express 4.x 和 Node.js 未定义 req.body

node.js - 在 Express.js 中使用相同的响应对象发送多个响应(res.json)

javascript - 计算返回 NaN

javascript - 使用express angularJs和mongoDB,但 Angular 中的ngResource未加载

node.js - 如何阻止 pm2 杀死分离的子进程