使用纯js将数据从node.js发送到前端

我正在尝试将带有数据的对象从 Node.js 服务器发送到 js 文件(用于在前端使用此数据)。


在文件main.js 中,我正在操作 DOM。我提出以下要求:


let dataName = [];

let request = async ('http://localhost:3000/') => {

    const response = await fetch(url);

    const data = await response.json();

    dataName = data.name;

}


let name = document.getElementById('name');

name.textContent = dataName;

然后在文件server.js我有一个对象:


data = [

    {

        "id": 1,

        "name": "Jhon"

    },

    {

        "id": 2,

        "name": "Mike"

    }

];

我想将它作为 json 字符串(或其他方式)发送到main.js作为对我请求的响应。


问题:我的数据显示在浏览器的窗口中。我怎么能得到它作为回应?


我试过


let express = require('express');

let app = express();

app.use(express.static(`main`));

app.get('/', function(req, res){

    res.json(data); //also tried to do it through .send, but there data only on window in browser

});

app.listen(3000);

有人可以告诉我要在我的代码中更改什么或指出我谷歌的方向吗?(我不想使用模板引擎)。


请帮助我 :) 愿你平安。


函数式编程
浏览 301回答 2
2回答

汪汪一只猫

我认为您正在尝试在同一个 URL 上提供您的前端和 JSON 数据/。您需要调整您的服务器代码如下:let express = require('express');let app = express();app.use(express.static(`main`));app.get('/api', function(req, res){    res.json(data); //also tried to do it through .send, but there data only on window in browser});app.listen(3000);现在您的数据将以 JSON 格式从/api. 然后你可以在前端发出如下请求:let dataName = [];let request = async () => {    const response = await fetch('http://localhost:3000/api');    const data = await response.json();    dataName = data.name;}let name = document.getElementById('name');name.textContent = dataName;还有一个问题是url没有正确定义为参数。我调整了函数以在正确的位置简单地使用 URL 字符串。

慕盖茨4494581

您可以创建一个可以使用REST API进行通信的服务器(假设数据是一个字符串)客户:let data = getSomeDataYouWantToSend()fetch('/send', {&nbsp; &nbsp; method: 'POST',&nbsp; &nbsp; headers: {&nbsp; &nbsp; &nbsp; 'Content-Type': 'text/plain'&nbsp; &nbsp; },&nbsp; &nbsp; body: data})假设您在目录中有静态文件,在目录中/main有 html 文件/views服务器:let express = require('express')let app = express()app.use(express.static(`${__dirname}/main`))app.set('views', `${__dirname}/views`)app.get('/', (req, res) => {&nbsp; &nbsp; res.render('index.html')})app.post('/send', (req, res) => {&nbsp; &nbsp; console.log(req.body) // <- here is your data sent from client frontend})app.listen(3000)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript