【问题标题】:Obtain result of GET request in javascript (and Node.js)在javascript(和Node.js)中获取GET请求的结果
【发布时间】:2020-12-01 01:04:58
【问题描述】:

单击按钮时,我试图从 Node.js 服务器获取基本的 GET 请求。

server.js

const express = require('express');
const app = express();
app.use(express.static("./public"));

app.listen(8080, () => {
  console.log(`Service started on port 8080.`);
});

app.get('/clicks', (req, res) => {
  res.send("foobarbaz");
})

client.js

document.getElementById("button").addEventListener("click", showResult);
function showResult(){
  fetch('/clicks', {method: 'GET'})
    .then(function(response){
      if(response.ok){
        return response;
      }
      throw new Error('GET failed.');
    })
    .then(function(data){
      console.log(data);
    })
    .catch(function(error) {
      console.log(error);
    });
}

但是,控制台日志显示:

Response {type: "basic", url: "http://localhost:8080/clicks", redirected: false, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "basic"
url: "http://localhost:8080/clicks"
__proto__: Response

如何获得我的“foobarbaz”?

如果我转到localhost:8080/clicks,文本会显示在那里。

此外,response 似乎已经是一个 javascript 对象 -- response.json() 不起作用。

【问题讨论】:

  • 您的服务器代码没有响应 JSON,所以这就是 response.json() 不起作用的原因。响应请求时需要设置 Content-Type 标头。我建议查看一些关于如何配置 express 以响应 JSON 的教程。 documentation talks about this in the Guide section.

标签: javascript node.js http get


【解决方案1】:

send() 参数应该是 JSON。将server.js 更改为

app.get('/clicks', (req, res) => {
  res.send({result:"foobarbaz"});
})

现在您将在client.js 中收到 JSON 作为响应,结果可以作为

function showResult() {
    fetch('/clicks', { method: 'GET' })
        .then(function (response) {
            if (response.ok) {
                return response.json();
            }
            throw new Error('GET failed.');
        })
        .then(function (data) {
            console.log(data.result);
        })
        .catch(function (error) {
            console.log(error);
        });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-07
    • 1970-01-01
    • 2018-12-15
    • 1970-01-01
    • 2023-01-02
    • 1970-01-01
    • 1970-01-01
    • 2013-11-01
    相关资源
    最近更新 更多