Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ajax 从主机上的静态HTML页面调用express(node.js)API_Ajax_Api_Express_Webserver_Static Html - Fatal编程技术网

Ajax 从主机上的静态HTML页面调用express(node.js)API

Ajax 从主机上的静态HTML页面调用express(node.js)API,ajax,api,express,webserver,static-html,Ajax,Api,Express,Webserver,Static Html,我有一个静态HTML页面,hello.HTML。如果双击hello.html,它将在默认浏览器中打开,并正确显示html,但在浏览器的搜索栏中,显示的不是带有主机名的URL,而是计算机上hello.html的本地文件路径 我使用express(node.js)在我的计算机上制作了一个简单的express web服务器。它被设置为侦听端口8080,并具有一个简单的GET api。(API现在执行一些简单的操作,比如调用“ls”)。我希望能够从静态hello.html调用GETAPI。在我的静态HT

我有一个静态HTML页面,hello.HTML。如果双击hello.html,它将在默认浏览器中打开,并正确显示html,但在浏览器的搜索栏中,显示的不是带有主机名的URL,而是计算机上hello.html的本地文件路径

我使用express(node.js)在我的计算机上制作了一个简单的express web服务器。它被设置为侦听端口8080,并具有一个简单的GET api。(API现在执行一些简单的操作,比如调用“ls”)。我希望能够从静态hello.html调用GETAPI。在我的静态HTML页面中,我使用jquery对该api进行ajax调用,将其称为。一旦启动express服务器并加载页面,查看控制台日志,当我在浏览器中加载静态HTML页面时,对myapi的请求就会通过(ls响应会记录在控制台上),然而,HTML页面中的jquery ajax始终执行错误函数,即使我将响应设置为200

我读了很多关于为什么会发生这种情况的书,读到这可能是因为CORS的问题。但是,在这种情况下,我无法在服务器端指定主机名,因为实际上没有web服务器在运行,因此没有与静态HTML页面关联的实际主机名

这可能吗?(要在您的计算机上有一个没有运行web服务器的静态HTML页面,请使用API创建您自己的express服务器,并从静态web页面调用这些API?)

例如:

hello.html

<html>
<head>
<title>Hello World</title>
</head>
<body>
<script src"js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
     $.ajax({
        type: "GET",
        url: "http://127.0.0.1:8080/myapi",
        contentType: 'application/json',
        success: function(response) {
               alert("success!");
        },
        error: function(jqXHR, textStatus, errorThrown) {
                alert("error");
        },
    });
});
</script>


<p>Hello World!</p>
</body>
</html>
我通过给出node myserver.js启动服务器,然后在浏览器中打开静态HTML页面。当它加载时,API调用正在进行,正如我看到的服务器端控制台输出一样,它正在成功进行。然而,回到静态html中,ajax调用的“error”函数总是被执行。

我让它工作了

以防其他任何人产生疑问,而且对于像我这样的express和web服务器来说是新的

关键是要有express serve hello.html。这样做很简单

我的express服务器位于如下目录中:

myserver/myserver.js
var express = require('express');
var shelljs = require('shelljs');
var app = express();

app.get('/myapi', function (req, res) {

      shellStr = shelljs.exec('ls');
      if ( shellStr ) {
            console.log("successful call on server side");
            res.status(200);
            res.json({ ls: shellStr });
      }
      else {
           console.log("failure status on server side");
           res.status(500).json({ error: "Could not do ls"});
      }
})

var server = app.listen(8080, function() {
     console.log("Listening on 8080");
})
app.use(express.static('myhtml'))