使用express发送和接收数据

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

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

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

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

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

javascript node.js express
1个回答
0
投票

这是一个简单的设置:

1)Express从执行client.js的public /文件夹提供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)=>{
    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

fetch("/json")
.then((res)=> res.json())
.then((data)=>{

    console.log( data );

})
.catch(console.error);

template.json

{"firstname":"john","lastname":"doe"}
© www.soinside.com 2019 - 2024. All rights reserved.