Node. js returns JSONP details, node. jsjsonp details

Source: Internet
Author: User

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.

Related Article

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.