Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to interact with JSONP in Node.js

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "how to interact with JSONP in Node.js". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to interact with JSONP in Node.js.

Implementing JSONP in Node.js is very simple. With the following code, we return and run a JavaScript function from the server. The JavaScript function has been defined in advance at the caller, 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 to be 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 called through JQuery:

Copy the code

Jsonp test

$(function () {)

$('# btn'). On ('click', function () {

$.get ('http://anothersite/api/getinfo', function (d) {

Console.log (d)

}, 'jsonp')

})

})

At this point, I believe you have a deeper understanding of "how to interact with JSONP in Node.js". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report