我是 Node.js 新手,我正在尝试将数据从 AJAX 发送到 Node.js 服务器并取回内容。我的服务器端代码是
var http = require('http');
var url=require('url');
http.createServer(function (req, res) {
console.log(req.url);
var url_parts = url.parse(req.url, true);
switch(url_parts.pathname)
{
case '/':
res.writeHead(302,{'location':'http://localhost/testajax/index.html'});
res.end();
break;
case '/test':
console.log('request received');
res.writeHead(200, {'Content-Type': 'text/html'});
console.log(url_parts.query["page"]);
res.end(url_parts.query["page"]);
break;
}
}).listen(8124);
在客户端运行的是
<script type="text/javascript">
$(document).ready(function() {
$('a').click(function(){
$.get('http://localhost:8124/test', {'page':$(this).text()}, function(data){
alert(data);
$('#content').html(data);
});
});
});
</script>
内容在 <div>
但这没有显示,也没有发出任何警报。在安慰浏览器时,我收到此错误。
XMLHttpRequest cannot load http://localhost:8124/test?page=ProfilePage. Origin http://localhost is not allowed by Access-Control-Allow-Origin.
这是一种错误的做事方式吗?请帮忙。
最佳答案
您似乎正在尝试向域外发出请求。看看这个答案:https://stackoverflow.com/a/9327231/1417431
您可以在这里进一步阅读:Same origin policy
关于ajax - AJAX 和 Node.js 交互的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13227287/