node.js - 我对 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 它可以工作!
所以它一定是我的节点服务器中的东西......
提前感谢您提供的任何帮助
有小费吗
解决方案
正如 hoangdv 在评论中所解释的,该解决方案包括在节点服务器上添加 CORS 支持。
在这里您可以找到一个很好的解释:Flavio Copes 在 Express 中处理 CORS
推荐阅读
- html - 视觉和布局视口和文档
- asp.net-mvc - asp.net mvc 从视图中排除 Id
- html - 背景图像悬停转换延迟
- javascript - JavaScript - 禁用提交按钮
- javascript - 解析 html 时 jQuery 不加载
- python - 如何在 boto3 中模拟 AWS CLI EC2 过滤器
- python - 为什么 mysql DB、表、列上的 utf8mb4 在插入特殊字符时出错?
- python - Map-Reduce 输入拆分未按预期工作
- linux - 如何使用 VMX 暂停和恢复 VM
- python - 读取 CSV,从字典中获取 Column 数据类型