Node. js returns JSONP details, node. jsjsonp details
When JQuery Ajax is used to request data from the server or send data to the server, errors that cannot be requested across domains are often encountered. A common solution is to use JSONP in Ajax. Based on security considerations, the browser will have a same-origin policy. However, the <script/> label has the ability to access data across domains, which is the basic principle of JSONP. The same-source policy and what is JSONP.
In Node. JSONP implementation in js is very simple. Through the following code, we return from the server and run a JavaScript function. This JavaScript function has been defined by the caller in advance, so it is automatically executed 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.Res. type ('text/javascript ')Before being added to the returned data, it is used to tell the browser that this is a piece of JavaScript code.
The front-end page is called through JQuery:
<!DOCTYPE html>
Run the code and click the button. On the console Panel of the browser, we can see the json object returned from the remote server.
The above Node. js response to JSONP is a detailed explanation of all the content that I have shared with you. I hope to give you a reference and support for the help house.