【问题标题】:Using the Javascript Fetch API with Hapi将 Javascript Fetch API 与 Hapi 一起使用
【发布时间】:2017-09-29 10:14:29
【问题描述】:

我用 Hapi 创建了一个简单的 API,它有一个可以 POST 到的路由,如下所示:

server.route({
  method: "POST",
  path: "/hello",
  handler: function(request, reply) {
    // It doesn't ever get to here
    return reply({hello: request.payload.name});
  },
  config: {
    validate: {
      payload: {
        name: Joi.string().required()
      }
    }
  }
});

我可以在 Postman 中成功向该路径发送 POST 请求: 它返回预期的响应。但是,当我使用这段 Javascript 发送请求时:

fetch("http://localhost:1111/hello", {
  mode: "cors"
  body: {name: "John Doe"}
}).then(() => {
  console.log("yay! it worked");
});

这失败了,并且说“值”必须是一个对象。

【问题讨论】:

    标签: post hapijs payload fetch-api


    【解决方案1】:

    事实证明,我只需要先对 JSON 进行字符串化,然后就可以了:

    fetch("http://localhost:1111/hello", {
      mode: "cors"
      body: JSON.stringify({name: "John Doe"})
    }).then(() => {
      console.log("yay! it worked");
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-14
      • 2017-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 2021-02-17
      相关资源
      最近更新 更多