In node. js, you can control the request and response, you can define your own response, such as how to respond to the text, how to respond to the JSON, how the image stream responds, and so on, which in the sails architecture, it becomes easier and clearer, it is located in the project's api/ In the responses directory, you can define your own response body.
In fact, sails for us to encapsulate some of the corresponding standard, such as the View method, which is a response body, it can be the text, JSON object rendering to the specified view, and we can imitate it to implement its own response body, the following code is an official given an example, Its method name is Myresponse, this is the sails schema a way to define the class module, that is, the JS file name is not your class name, we can in the program through the Res.myresponse ("Your response content") to call it, the specific code is as follows
/** * Api/responses/myresponse.js * * This would be available in controllers as Res.myresponse (' foo ');*/Module.exports=function(message) {varreq = This. req; varres = This. Res; varViewfilepath = ' Myspecialview '; varStatusCode = 200; varresult ={Status:statuscode}; //Optional Message if(message) {Result.message=message; } //If The user-agent wants a JSON response, send JSON if(Req.wantsjson) {returnRes.json (result, result.status); } //Set Status Code and view localsRes.status (result.status); for(varKeyinchresult) {Res.locals[key]=Result[key]; } //and render ViewRes.render (Viewfilepath, result,function(err) {//If The view doesn ' t exist, or an error occured, send JSON if(err) {returnRes.json (result, result.status); } //Otherwise, serve the ' views/myspecialview.* ' pageRes.render (Viewfilepath); });};
It implements two responses to normal files and JSON objects, and we call it in code the same way as the view class.
module.exports={ function (req, res) { return Res.view ({title: "Uncle", Engtitle: "Lind"}); // return Res.view ("view_name", data)//view_name parameter is null for the current action },err: function (req,res) { return res.myresponse ({errcode:0,error: "generates error"});};
Get the following results by executing Http://localhost:1337/test/err
The above features are similar to the rewrite Viewresult in C # MVC, which controls the output response stream.
node. JS and sails~ Custom Response response body