在koa.js路线中发送带标题的发布请求

时间:2016-06-28 01:33:30

标签: javascript node.js request koa

我正在尝试在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)

我只想重新设置serverA到serverB的路由。这种方法有误吗?

1 个答案:

答案 0 :(得分:4)

如果你想从serverA向serverB发送请求,我就你想要实现的目标创建了一个示例应用程序。

time_elapsed_string

服务器A SELECT COUNT(distinct TRANSPORTNO) as cnt, month(DATEASKED) as date_month FROM TRANSPORTARCHIVE GROUP BY month(DATEASKED); )有一个名为'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); 的端点,使用appA方法,访问它会向{strong发送/v3_6/autoevents个请求>服务器B 的GETPOST端点作为回报,将使用A&#39的请求正文和appB发送截断值。

使用/v3_6/autoevents在浏览器上执行后的最终输出将为Hello World from B;