在nodejs服务器和ABAP服务器上使用jsonp
  TEZNKK3IfmPf 2023年11月14日 15 0

In my blog Cross domain request in ABAP and Java with two workaround I introduce the step how to deal with Cross Domain issue using Cross-origin resource sharing ( CORS ) supported by almost all modern browsers.

And there is another alternative for cross domain issue, that is JSONP which can work on legacy browsers which predate CORS support.

In this blog, I will first explain how to use JSONP and then introduce the secret behind it.

JSONP in nodeJS server

Suppose I have two employee ID lookup service hosted by the port 3000 and 3001 in my local server. The service will simply return employee name by ID.

The client web page is hosted in port 3000. According to same origin policy, the web page hosted in port 3000 is allowed to access the service hosted in localhost:3000, but forbidden for localhost:3001.

在nodejs服务器和ABAP服务器上使用jsonp

Let’s now do a verification.
This is my server listening to port 3000:

const express = require('express');  
const app = express();  
const port = 3000;

var path = require('path');
var repo = {
	"I042416": "Jerry",
	"I042417": "Tom",
	"I042418": "Jim"
}
app.use(express.static(path.join(__dirname, 'public')));

app.get('/request', (request, response) => {  
 console.log("The employee ID sent from Client:" + request.query.id);
  response.json({
    UserName: repo[request.query.id] + " ( handled in port 3000 )"
  });
});
app.listen(port, (err) => {  
  if (err) {
    return console.log('something bad happened', err)
  }
  console.log(`server is listening on ${port}`)
});

And this is my client page which allows end user to type the employee ID and send the query request:

<html>
<body>
<form action="">
  ID: <input type="text" id = "inumber" name="ID" value="I042416"><br>
  <input type="submit" value="Submit">
</form> 
</body>
<script src="jquery1.7.1.js"></script>
<script>
$(document).ready(function(){	
     $("form").click(function(e){
     	e.preventDefault();
        var data = {
            id: $("#inumber").val()
        };
        $.ajax({
            type: 'GET',
            data: data,
            url: 'http://localhost:3000/request',
            dataType: 'json',
            success: function(data) {
                alert(data.UserName);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log('error ' + textStatus + ' ' + errorThrown);
            }
        }); 
    });
});
</script>
</html>

When I click Submit button, I get query response returned from service in port 3000 as expected:

在nodejs服务器和ABAP服务器上使用jsonp
在nodejs服务器和ABAP服务器上使用jsonp

And this is the log output in the console of service in port 3000:

在nodejs服务器和ABAP服务器上使用jsonp

Now I make small modification on the web page in port 3000, forcing it to send request to port 3001 instead:

在nodejs服务器和ABAP服务器上使用jsonp

And resend the id query, this time I saw the expected cross domain error message:

在nodejs服务器和ABAP服务器上使用jsonp

How to resolve cross domain issue using JSONP

Both minor changes in client and server side are necessary.

In service working in port 3001, I add a new service end point “request_jsonp”:

app.get('/request_jsonp', (request, response) => {  
  console.log("This service supports JSONP now: " + request.query.id);
  var data = "{" + "UserName:'" + repo[request.query.id] + " ( handled in port 3001 )'"
  + "}";
  var callback = request.query.callback;
  var jsonp = callback + '(' + data + ');';
  response.send(jsonp);
  response.end();
});

In client web page, I change the send AJAX data type from json to jsonp, and inform server that “please parse the callback function name from literal “callback” in request header.

$.ajax({
            type: 'GET',
            data: data,
            url: 'http://localhost:3001/request_jsonp',
            dataType: 'jsonp',
            jsonp: 'callback',
            jsonpCallback: 'jsonpCallback',
            success: function(data) {
                alert(data.UserName);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log('error ' + textStatus + ' ' + errorThrown);
            }
        }); 

Now send the query again from localhost:3000 page, and the request could successfully reach service in localhost:3001, handled there and return to localhost:3000 again:

在nodejs服务器和ABAP服务器上使用jsonp

Magic behind JSONP

In fact, no magic at all. The mechanism of JSONP just utilize the “benefit” that the HTML

 
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年05月31日   30   0   0 服务器
  TEZNKK3IfmPf   2024年05月17日   42   0   0 linux服务器
  TEZNKK3IfmPf   2024年05月31日   52   0   0 linux服务器
  TEZNKK3IfmPf   2024年05月31日   30   0   0 linux服务器centos
  TEZNKK3IfmPf   2024年05月31日   43   0   0 服务器java
  TEZNKK3IfmPf   2024年05月31日   37   0   0 服务器http
TEZNKK3IfmPf