繁体   English   中英

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

[英]Obtain result of GET request in javascript (and Node.js)

当我单击一个按钮时,我试图从 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”?

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM