node. JS returns JSONP

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.