Nut
Nut

Reputation: 11

Koa.js request-promise return [ The property , ' ' , in the request body is invalid ]

I try to post json to Line' messaging api with koa.js and request-promise but got error as attached image :

POST-error-400-request-body-is-invalid
POST-error-400-request-body-is-invalid-2

I'm using heroku with koa.js to connect with Line messaging api.
Here is my code :

const Koa = require('koa');
const Router = require('koa-router');
const logger = require('koa-logger');
const bodyParser = require('koa-bodyparser');
const app = new Koa();
const router = new Router();
const port = process.env.PORT || 4000;
app.use(logger());
app.use(bodyParser());

app.on('error', (err, ctx) => {
    console.log('server error', err, ctx)
});

app.use(router.routes());
app.use(router.allowedMethods());

router
    .get('/', (ctx, next) => {
        console.log(ctx);
        ctx.body = ctx;
    })
    .post('/webhook', async (ctx, next) => {
        var reply_Token = ctx.request.body.events[0].replyToken;
        console.log('token = ' , ctx.request.body.events[0].replyToken);

var rp_body = JSON.stringify({
    replyToken: reply_Token,
    messages: [{
            type: 'text',
            text: 'Hello'
        },
        {
            type: 'text',
            text: 'How are you?'
        }]
    });
var options = {
    method: 'POST',
    url: 'https://api.line.me/v2/bot/message/reply',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer {xxxxxxxx}'
    },
    json: true,
    body: rp_body
};
var rp = require('request-promise');
rp(options)
    .then(function (parsedBody){
        console.log('rq success');
    })
    .catch(function (err) {
        console.log('server error', err, ctx);
    });
});

app.listen(port);
module.exports = { app }

After try to solving with changing variable but seem doesn't work at all. This is what I try to adapt from using Node.Js to Koa.js.

Upvotes: 0

Views: 550

Answers (1)

Nut
Nut

Reputation: 11

Solving the problems!, thanks to @num8er for pointing to it.

As the body entity has 'json : true' so the body is already stringify by this. There's no need to do stringify before.

So removing it like :

var rp_body = JSON.stringify({ 
replyToken: reply_Token,
messages: [{

to

var rp_body = ({
replyToken: reply_Token,
messages: [{

However after pull off stringify from body you might encounter 'Invalid Token' if process api.line.me verification.

It's what it should be, because api.line.me will throw zeros as reply token for verification and Koa.js look at it like an error.

So checking for if token is zeros then send status 200 to complete the verification, otherwise do the POST METHOD if token is not zeros.

if(reply_Token === '00000000000000000000000000000000') {
    ctx.status = 200;
} else {
    //POST METHOD
}

enter image description here enter image description here

Upvotes: 0

Related Questions