【问题标题】:Sending and receiving data with express使用 express 发送和接收数据
【发布时间】:2020-02-09 11:19:14
【问题描述】:

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

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

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


任何解决方案,甚至只是指针都表示赞赏。

【问题讨论】:

  • 您研究过 Ajax 并获取 API 吗?
  • 我研究了 AJAX,但没有听说过,将不得不研究,获取。

标签: javascript node.js express


【解决方案1】:

这是一个简单的设置:

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);

template.json

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

参考资料:

【讨论】:

  • 如果我要创建一个包含多个 json 文件的文件夹,我必须单独要求每个文件还是需要整个文件夹?
  • 是的,您必须通过某种循环单独要求每个文件。 @kevinuulong 也许这些会有所帮助:stackoverflow.com/questions/10049557/…
猜你喜欢
  • 1970-01-01
  • 2011-08-06
  • 2019-09-12
  • 1970-01-01
  • 1970-01-01
  • 2011-10-24
  • 1970-01-01
  • 2017-02-19
  • 2016-09-11
相关资源
最近更新 更多