Warm tip: This article is reproduced from serverfault.com, please click

其他-获取javascript(和Node.js)中GET请求的结果

(其他 - Obtain result of GET request in javascript (and Node.js))

发布于 2020-11-30 16:32:21

当我单击按钮时,我想从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()不起作用。

Questioner
Alex Coleman
Viewed
11
Shabir Hamid 2020-12-01 01:04:58

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

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

现在你将收到一个JSON作为响应,client.js结果可以用作

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