我有一个nodejs应用程序,它发送带有标题为application/json
的响应。客户端正在发出http
ajax请求并获得200 OK状态。我还能够从Rest Client查看json响应。
但我没有在UI上看到任何回复。请让我知道我哪里出错了。
我的Firefox上的Firebug控制台:
Connection:keep-alive
Content-Length:30
Content-Type:application/json; charset=utf-8
Date:Wed, 15 Jun 2016 12:13:34 GMT
ETag:W/"1e-p2J1WXSidVD0/pV2ACqLcQ"
X-Powered-By:Express
Request Headers
view source
节点js代码:
var express = require('express');
var app = express();
app.get('/button', function (req, res) {
res.set('Content-Type', 'application/json');
res.send('{"name":"<input type=button>"}');
res.end("response sent");
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
在客户端:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login Form</title>
<script type="text/javascript" src="js/loginDemo.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>
<body onload="loadPage()">
<div id="loginForm">
</div>
</body>
</html>
在剧本方面:
$.get("http://172.28.88.28:8081/button",
function(data, status){
alert("Data: " + data + "\nStatus: " + status);
}, function(err){
alert('error > '+err);
});
答案 0 :(得分:0)
同源策略 - 我相信是你的问题...我在你的代码中看到你使用端口8081是你的请求是来自同一个域的相同协议和同一个端口(8081)? ... https://en.wikipedia.org/wiki/Same-origin_policy 如果你没有添加代码来显示你的ajax请求中的错误......你就不会 在网络标签中看到此错误... 在你的代码中尝试这个:
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://yourClientAddress:8081');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);