如何正确模拟路由器 PUT

Howto Koa Router PUT done right

[因为koa-router维护者想在Whosebug上问我开了一个账户]

编辑这是关于你通过'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 Headers 顺便说一句。 其他路线如 GET 和 DELETE 工作正常。

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

如果您想要实现的只是return发送的数据,请使用request.body而不是response:

ctx.body = ctx.request.body;

一般来说,PUT 请求与 post 请求相同。

您还需要一个正文解析器中间件,例如 koa-bodyparser(link) or koa-body (link).

如您所述,这是您的 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