【发布时间】:2018-12-10 05:17:03
【问题描述】:
我正在尝试创建一个专用于 Ajax 请求的私有页面。这是简单的请求。
window.onload = loaded;
function loaded(){
var xhr = new XMLHttpRequest();
xhr.open('GET', '/data_annotations', true);
xhr.onload = function(){
if(this.status == 200){
var data = xhr.responseText;
console.log(JSON.parse(data));
} else {
console.log("Rip");
}
}
xhr.send();
//httpreq.abort();
}
这是它运行的 node.js:
...
app.get('/', function(req, res, next){
console.log("Connected Successfully.");
res.render('home');
});
app.get('/data_annotations', function(req, res, next){
if(req.xhr || req.headers.accept.indexOf('json') > -1) {
const mc = mongo.MongoClient;
const url = 'mongodb://localhost:27017/';
const dbName = 'practiceMDB';
console.log("Got Data Annotations.");
mc.connect(url, { useNewUrlParser: true }, (err, client) =>{
if(err){
console.log(err);
} else {
const db = client.db(dbName);
data = db.collection('DataAnnotations');
data.find({}).toArray(function(err, data){
res.send(data)
});
client.close();
}
});
} else {
res.redirect('/');
}
});
app.listen(port, function(){
console.log('Server Started on Port '+port);
});
我只希望 /data_annotaion 来自 Ajax 请求时运行。如果用户在 url 中输入 /data_annotations,它应该将他们重定向到主页。当我运行它时,我得到了这些结果:
Server Started on Port 3000
Connected Successfully.
Connected Successfully.
这表明(对我而言)ajax 请求没有注册为 ajax 请求,而是注册为正常请求。此外,我收到此错误:
Uncaught SyntaxError: Unexpected token < in JSON at position 0
我相信这是由于重定向。 Ajax 请求被重定向,它获取主页的响应并且无法解析它(我相信这是因为它无法解析 HTML 文本或字符串文本 - 不要引用我的话)。如何让 Node JS 注册我的 Ajax 请求?
PS:我查看了这个答案以确定请求是否是 Ajax,但它总是将我的请求确定为不是 Ajax:https://stackoverflow.com/a/28540611/6804700
【问题讨论】:
-
是什么让您认为
res.send(data)正在发送 JSON?您的客户需要 JSONJSON.parse(data)- 如果您不发送 JSON,您将在此处收到错误...和 req.headers.accept.indexOf('json')... 请求标头是否包含带有确切 4 个字符的接受json? -
@JaromandaX 抱歉,我对使用 Ajax 和 JSON 很陌生。
-
好吧...检查浏览器开发者工具控制台。您应该能够准确地看到请求和响应的样子,包括标头 - 提示:
Accept可能是*/* -
如果您想避免将内容提供给普通浏览器 URL,我建议您使用自己的自定义标头。
-
@JaromandaX 它说它来自主页(这是真的),但 Ajax 请求正在发送到
/data_annotations
标签: javascript node.js ajax express