Howto Koa Router PUT正确完成

时间:2018-07-17 14:09:45

标签: node.js rest router put koa

[因为koa-router维护者希望在stackoverflow上询问我开设了一个帐户]

编辑这是关于您通过“ npm install koa-router”获得的NPM

如何正确使用Koa-Router和PUT将数据发送到服务器?

我会这样:

// trivial stuff ommitted
router.put('/devices/myDevice',  (ctx, next) => {
    console.log('ctx:',ctx);
    ctx.body = "nothing in ctx which looks like my data: whatever"
    next();
});

和客户端:

fetch('http://localhost:3000/devices/myDevice',{
            method: 'PUT',
            data: "whatever"
        })
        .then(function(data){
            return data.json();
        }).then(function(res){
        })
        .catch(function(err) {
            console.log('Fetching myDevice Error:', err);
          });

这样做,我的ctx看起来像这样:

ctx: { request:
{ method: 'PUT',
 url: '/devices/myDevice',
 header:
  { host: 'localhost:3000',
    connection: 'keep-alive',
    'content-length': '0',
    origin: 'null',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) 
     AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 
     Safari/537.36',
    accept: '*/*',
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7' } },
    response:
    { status: 404,
    message: 'Not Found',
    header: { vary: 'Origin', 'access-control-allow-origin': 'null' } },
     app: { subdomainOffset: 2, proxy: false, env: 'development' },
    originalUrl: '/devices/myDevice',
    req: '<original node req>',
    res: '<original node res>',
     socket: '<original node socket>' }

可以看到我得到了404,但是路由被触发到console.log(ctx)... 我也看不到尝试发送到服务器的数据。 Cors标头设置为btw。 其他路线,例如GET和DELETE都可以正常工作。

这是一个错误还是有人可以重现所描述的行为?

2 个答案:

答案 0 :(得分:0)

如果您要实现的只是返回发送的数据,请使用session('foo')而不是request.body

response

通常,将ctx.body = ctx.request.body; 请求与发布请求相同。

您还需要一个正文解析器中间件,例如PUTlink)或koa-bodyparserlink)。

答案 1 :(得分:0)

正如您提到的,这是您的fetch的问题。在选项中包含body属性(不是data)。

用法示例:

fetch('http://localhost:3000/devices/myDevice', {
  method: 'PUT',
  body: JSON.stringify({ name: 'john', age: 30 })
})
  .then(function(data) {
    return data.json();
  })
  .then(function(res) {})
  .catch(function(err) {
    console.log('Fetching myDevice Error:', err);
  });

获取文档:https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch