首页 文章

Howto Koa路由器PUT做得对

提问于
浏览
0

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

Edit :这是关于你通过'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这样的其他路由工作正常 .

这是一个错误还是那里的任何人都可以重现所描述的行为?

2 回答

  • 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

  • 0

    如果要实现的只是返回发送的数据,请使用 request.body 而不是 response

    ctx.body = ctx.request.body;
    

    通常,将 PUT 请求与发布请求相同 .

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

相关问题