Node.js return JSONP Detailed _node.js

Source: Internet
Author: User

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:

<! DOCTYPE html>
 
 

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.

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.