JSONP - express:为什么浏览器会忽略请求?

JSONP - express: Why does the browser ignore the request?

我编写了以下 HTML 文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>HTML page</title>
</head>

<body>
    <script src='http://localhost:3000?callback=mycallbackFunction'> </script>
    <script>
        function mycallbackFunction(data) {
            alert('here');
            alert (data['a']);
        }
    </script>
</body>

</html>

如您所见,脚本标记包含对远程服务器的 JSONP 请求。

此外,我编写了以下 node.js 文件并将其 运行 作为服务器:

var express = require('express'); var app = express();

app.get('/', function(req, res) {
   res.jsonp({'a': 'blabla'});
});

app.listen(3000);

在我获得 运行 node.js 文件并打开带有 html 页面的浏览器后,我希望看到 window 弹出警报。但不是。我什么也没看到。

开发者工具中的网络选项卡显示请求已被接受:

你知道怎么解决吗?

您需要调换 <script> 个元素的顺序。

解释:

Express 正确地提供了一个类似于 myCallbackFunction({'a': 'blabla'}) 的脚本,这正是您所希望的。但是,此脚本立即运行,并且 myCallbackFunction 尚未定义,因此什么也没有发生。然后,在下一个 <script> 块中,您定义 myCallbackFunction,但这是无用的,因为(失败的)调用已经发生在之前的 <script>.

此外,mycallbackFunction 中的 C 大小写不匹配 - 确保回调参数和函数名称的大小写一致。

解决办法是调换两个脚本标签的顺序:

<body>
    <script>
        function mycallbackFunction(data) {
            alert('here');
            alert (data['a']);
        }
    </script>
    <script src='http://localhost:3000?callback=mycallbackFunction'>  </script>
</body>