Using jquery Ajax to request data from the server or to send data to the server often encounters a cross-domain error that cannot be requested, and the common solution is to use JSONP in Ajax. Based on security considerations, the browser will have a homology policy, but the <script/> tag has the ability to access data across domains, which is the basic principle of JSONP work. About homology policies and what is JSONP.
Implementing JSONP in Node.js is very simple, and the following code enables us to return and run a JavaScript function from the server, which is already defined in advance by the caller and automatically executes when it is returned.
var express = require (' Express ');
var router = Express. Router ();
Router.get ('/getinfo ', function (req, res, next) {
var _callback = req.query.callback;
var _data = {email: ' example@163.com ', Name: ' Jaxu '};
if (_callback) {
res.type (' Text/javascript ');
Res.send (_callback + ' (' + json.stringify (_data) + ') ');
}
else{
Res.json (_data);
}
);
Module.exports = router;
The code must specify the type of data returned from the server, and the Code res.type (' Text/javascript ') is added before the returned data to tell the browser that this is a piece of JavaScript code.
The front-end page is invoked through jquery:
Run the code, click on the button, in the browser's console panel we can always see the JSON object returned from the remote server.
The above this article Node.js return JSONP detailed explanation is small arranges to share to everybody's content, hoped can give everybody a reference, also hoped that everybody supports the cloud habitat community.