【问题标题】:send a post request with header in koa.js routes在 koa.js 路由中发送带有标头的 post 请求
【发布时间】:2016-06-28 01:33:29
【问题描述】:

我正在尝试在 koa.js 路由中发送带有标头的发布请求,如下所示:

这里是请求函数

const request = require('request').defaults({
  json: true
});

function *requestPromise(url, method, header, body) {
  return new Promise(function (resolve, reject) {
    delete  header["content-length"];
    let newHeader = {
      "user-agent": header["user-agent"],
      "host": header["host"],
      "connection": 'keep-alive'
    };
    console.log(newHeader)
    request({
      method: method,
      url: url,
      body: body,
      headers: newHeader
    }, function(error, httpResponse, body) {
      if (error) {
        console.error(url + " : " + error);
      } else if (httpResponse.statusCode !== 204) {
        reject(body.message);
      } else {
        resolve(body);
      }
    });
  });
}

这里是路线:

    router.post('/v3_6/autoevents', function *() {
        // save to db
        yield EventAuto.save(this.request.body);

        let akkaEndConfig = {
            url: "http://127.0.0.1:8080/v3_6/autoevents",
            method: 'POST',
            header: this.header,
            body: this.request.body
         };

         // request to another server 
         yield requestPromise(akkaEndConfig.url, akkaEndConfig.method, akkaEndConfig.header, akkaEndConfig.body);

         this.status = 204;
    });

但是当我想运行这个服务器时,得到了这个错误:

xxx POST /api/v3_6/autoevents 500 195ms -
TypeError: Cannot read property 'name' of undefined
        at Object.callee$1$0$ (/koa/src/lib/error-trace.js:10:11)
        at tryCatch(/koa/node_modules/regenerator/runtime.js:61:40)
        at GeneratorFunctionPrototype.invoke [as _invoke](/node_modules/regenerator/runtime.js:328:22)
        at GeneratorFunctionPrototype.prototype.(anonymous function) [as throw] (/node_modules/regenerator/runtime.js:94:21)
        at onRejected (/node_modules/co/index.js:81:24)
        at run (/node_modules/core-js/modules/es6.promise.js:104:47)
        at /node_modules/core-js/modules/es6.promise.js:115:28
        at flush (/node_modules/core-js/modules/$.microtask.js:19:5)
        at doNTCallback0 (node.js:428:9)
        at process._tickDomainCallback (node.js:398:13)

我只是想从服务器 A 到服务器 B 的路由中请求。这个方法错了吗?

【问题讨论】:

    标签: javascript node.js request koa


    【解决方案1】:

    如果您想从服务器 A 向服务器 B 发送请求,我创建了一个示例应用程序来说明您想要实现的目标。

    'use strict';
    var koa = require('koa');
    var route = require('koa-route');
    var request = require('request-promise');
    var rawBody = require('raw-body');
    
    var appA = koa();
    var appB = koa();
    
    appA.use(route.get('/v3_6/autoevents', function *(){
      let response = yield request({
        method: 'POST',
        url: 'http://127.0.0.1:8081/v3_6/autoevents',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ param1: 'Hello World from A' })
      });
    
      this.body = response;
    }));
    
    appB.use(route.post('/v3_6/autoevents', function *(){
      this.req.body = yield rawBody(this.req,{limit:'10kb', encoding:'utf8'});
      this.req.body = JSON.parse(this.req.body);
      this.body = 'Hello from World B; ' + this.req.body.param1;
    }));
    
    appA.listen(8080);
    appB.listen(8081);
    

    服务器 A(appA) 有一个名为 /v3_6/autoevents 的端点,使用 GET 方法,访问它会向 服务器 B 发送一个 POST 请求' s( appB ) /v3_6/autoevents 端点,作为回报将发送一个带有 A 的请求正文和 Hello World from B; 的截断值。

    在浏览器上使用http://127.0.0.1:8080/v3_6/autoevents 执行后的最终输出将是Hello World from B; Hello World from A

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-24
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    • 2021-08-13
    • 2014-07-27
    • 2017-02-07
    • 2021-12-03
    相关资源
    最近更新 更多