When Ajax uses jquery to request data from a server or send data to the server, it often encounters cross-domain errors that cannot be requested, and the common solution is to use JSONP in Ajax. Based on security considerations, the browser will have the same origin policy, but the <script/> tag has the ability to access data across domains, which is the basic principle of JSONP work. You can refer to this article in the garden for the same-origin strategy and what is JSONP http://www.cnblogs.com/yuzhongwusan/archive/2012/12/11/2812849.html
Implementing JSONP in node. JS is very simple, with the following code we return from the server and run a JavaScript function, the JavaScript function has been defined in advance by the caller, so when it is returned, it is executed automatically.
var Express = require (' Express ' var router = Express. Router (); Router.get ( '/getinfo ', function (req, res, next) { var _callback = Req.query.callback; var _data = {email: ' [email protected] ', Name: ' Jaxu ' ); else {Res.json (_data); }}); module.exports = router;
The code must specify the type of data returned from the server, and 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 called through jquery:
<!DOCTYPE HTML><HTMLLang= "en"><Head> <MetaCharSet= "UTF-8"> <title>JSONP Test</title> <Scriptsrc= "/bower_components/jquery/dist/jquery.js"></Script></Head><Body> <inputtype= "button"value= "click"ID= "BTN"> <Scripttype= "Text/javascript"> $(function(){ $('#btn'). On ('Click', function() {$.get ('Http://anothersite/api/getinfo', function(d) {console.log (d); }, 'Jsonp'); }); }); </Script></Body></HTML>
Run the code, click the button, in the browser's console panel we can always see the JSON object returned from the remote server.
node. JS returns JSONP