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