首页 > 解决方案 > 我对 Node JS 服务器的第一次浏览器 Ajax 调用(不起作用)

问题描述

在这里和那里阅读(主要在 stackoverflow 上)我创建了我的第一个节点服务器:

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

app.get('/', function (req, res) {
    res.send('Hello World!');
});

app.listen(3000, function () {
    console.log('Example app listening on port 3000!');
});

如果我使用 Google Chrome 形式的 URL,它可以完美运行:

在此处输入图像描述

但是,如果我使用带有一些 ajax 代码的简单客户端 html 页面,它不会显示任何内容:

<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <style media="screen">
    body {
      font-family: Helvetica;
      text-align: center;
    }

    #birthday-greeting {
      font-size: 72px;
      color: red;
      text-transform: uppercase;
    }
  </style>
  <body>
      <h1>Today's your special day!</h1>
      <button id="reveal" onclick="sendTheAJAX()" class="button">Why's that?</button>
      <div id="ajax-content">
      </div>
  </body>
  <script type="text/javascript">
    function sendTheAJAX() {
      xmlhttp = new XMLHttpRequest();
      //xmlhttp.open("GET","https://codepen.io/eclairereese/pen/BzQBzR.html", true);
      xmlhttp.open("GET","http://localhost:3000/", true);
      xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
          str = xmlhttp.responseText
          alert(str);
          document.getElementById('ajax-content').innerHTML = str;
        }
      }
      xmlhttp.send();
      document.getElementById('reveal').style.display = 'none';
    }
  </script>
</html>

还请考虑,如果我将本地节点 URL http://localhost:3000/替换为在网络上找到的另一个 URL:https ://codepen.io/eclarereese/pen/BzQBzR.html 它可以工作!

所以它一定是我的节点服务器中的东西......

提前感谢您提供的任何帮助

有小费吗

标签: node.jsajax

解决方案


正如 hoangdv 在评论中所解释的,该解决方案包括在节点服务器上添加 CORS 支持。

在这里您可以找到一个很好的解释:Flavio Copes 在 Express 中处理 CORS


推荐阅读