diggzhang
diggzhang

Reputation: 547

send a post request with header in koa.js routes

I'm trying to send a post request with header in koa.js routes like this:

Here is request function

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);
      }
    });
  });
}

Here is route:

    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;
    });

But when I wanna run this server,got this error:

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)

I just wanna requset form serverA's route to serverB. Is this method wrong?

Upvotes: 1

Views: 3815

Answers (1)

megamoth
megamoth

Reputation: 693

If you want to send a request from serverA to serverB, I created a sample app on what you want to achieve.

'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);

Server A( appA ) has an endpoint named /v3_6/autoevents using GET method, accessing it will send a POST request to Server B's( appB ) /v3_6/autoevents endpoint that in return will send a truncated value with A's request body and Hello World from B;.

The final output after you execute it on the browser using http://127.0.0.1:8080/v3_6/autoevents will be Hello World from B; Hello World from A

Upvotes: 4

Related Questions