TCG Development Log (6) Koa-body and JSON transfer

Source: Internet
Author: User

When the JSON is passed in HTTP between the server and the client, the request can now be initiated with a fetch from the client:

var datas = {
Foo:1,
Bar:2
}

var ret = await fetch ('/api/', {
Method: ' POST ',
headers:{
' Content-type ': ' Application/json '
},
Body:JSON.stringify (Datas)
});

Originally in the URL after the fetch should be filled in localhost:3000/api, but in the local debugging there is a cross-domain problem, you can set the Webpack-dev-server agent to solve.

Add the proxy entry in the Webpack.config.js devserver:

devserver:{
proxy:{
'/api/* ': {
Target: "Http://localhost:3000/",
Secure:false
}
}
}

Service side, at this time in App.use (Async ctx=>{}), can indeed receive the corresponding CTX, but how to get the JSON sent by the client? You can't get it with Ctx.req.body or ctx.request.body.

Here's how to do this:

Ctx.req.on (' Data ', function (data) {
Console.log (data);
})

Log out of data is a char buffer:

In contrast to ASCII, it is the body that was previously JSON: {"foo": 1, "Bar": 2}, of course, it is not possible to handle it yourself, a bit of trouble.

KOA a middleware koa-body can easily handle this problem, install it first:

NPM Install Koa-body--save

Before handling the body, the middleware is executed first, and the middleware will store the final results in the ctx.request.body.

Import koabody from ' Koa-body ';

.....

App.use (Koabody ({}));

App.use (Async ctx=>{
Console.log (Ctx.request.body);

Ctx.body = {
Message: "Hello!"
}
})

So you can see the body of the foo:1 and Bar:2, by the way, with Ctx.body to return a JSON to the client, the client can be handled as follows:

var Retjson = await Ret.json ();

Using the above method, the server and the client can send JSON to each other.

TCG Development Log (6) Koa-body and JSON transfer

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.