【问题标题】:How to call fetched method in ClientSide to receive an array from ServerSide?如何在客户端调用 fetch 方法从服务器端接收数组?
【发布时间】:2018-04-26 12:04:27
【问题描述】:

服务器端(app.js):

我从数据库中获取一些数据并将其放入数组中

app.post('/sendform', (req,res) =>{
        var array = [{"h":"1"},{"e","2"}];
        res.send(array);
)}

客户端(client.js):

我想获取该数组并将其添加到我的 index.html

function tableContent(){
     fetch('/')
        .then(res => {
        console.log(res);
        if(res.ok) return res.json();


 });
     .then(data => {

         //do something with html file
     });

}

【问题讨论】:

  • 顺便说一句,我的 post 方法通过我的 html 中的表单调用。
  • 不清楚您要做什么。您在 url 上有一个快速 POST 路由 sendForm,但您有客户端向 / 发出 GET 请求。如果您希望客户端从中获取任何内容,您需要一个路由来处理 / 请求。
  • 您无法获得相同的数组。您必须编写另一个端点 / 来获取您想要的数据

标签: javascript html node.js express


【解决方案1】:
    var URL = “127.0.0.1:3000/sendform”;

    var req = new Request(URL, {method: 'POST', cache: 'reload'});

    fetch(req).then(function(response) {
        var reader = response.body.getReader();
        return reader.read();
    }).then(function(result, done) {
        if (!done) {
        // do something with each chunk
        }
    });

POST 方法请求你的地址

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 2011-03-21
    • 1970-01-01
    • 2013-10-25
    相关资源
    最近更新 更多