使用javascript调用expressjs restful webservice => result总是空的响应

目的:
1)创build一个运行在NodeJsnetworking服务器上的网站。 (expressjs,stylus,jade)+ NodeJS
2)在NodeJsnetworking服务器(expressjs)+ NodeJS上创build一个宁静的web服务
3)网站调用一个宁静的Web服务条目(JavaScript文件)


随着Ubuntuterminal,我开始为网站nodeJs另一个为其余的webservice.Testing平静的web服务(在浏览器中):

地址:本地主机:1337 /酒/

数据结果是:[{“name”:“新酒”,“年”:“2012”,“_id”:“50e8255197f0b5260f000001”}]

testing网站Url:localhost:3000 /

这是我在网站上使用的JavaScript文件,在这里我想调用其余的url localhost:1337 / wines / en获取结果数据。

alert('hello!'); (popup) var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://localhost:1337/wines/'); xhr.onreadystatechange = function () { if (this.status == 200 && this.readyState == 4) { console.log('response: ' + this.responseText); alert("Yes"); } }; xhr.send(); 

在terminal,我看到GET被执行:
宁静的docker:
GET /葡萄酒/ 200 3ms – 93

网站terminal:
GET / 200 11ms
GET /JavaScript/script.js 304 1ms
GET /stylesheets/style.css 304 1ms

当我debugging我这样做:
var xhr = new XMLHttpRequest(); 好
xhr.open('GET','http:// localhost:1337 / wines /'); 好
xhr.send(); 好

xhr.onreadystatechange = function()跳入callbackOK
但'readystate = 4,但this.status = 0',我没有给出结果

最后我得到这个错误:
组件返回的失败代码:0x80004005(NS_ERROR_FAILURE)


来自firebug的结果信息(用于debugging此Java脚本)

内容types的应用程序/ JSON; 字符集= utf-8的
date星期日,06一月2013 04:15:07 GMT
X-Powered-By Express
请求头
接受text / html,application / xhtml + xml,application / xml; q = 0.9, / ; q = 0.8
接受编码gzip,放气
Accept-Language en-us,en; q = 0.5
连接保持活着
主机localhost:1337
起源//本地主机:3000
Referer // localhost:3000 /
User-Agent Mozilla / 5.0(X11; Ubuntu; Linux x86_64; rv:13.0)Gecko / 20100101
火狐/ 13.0.1


我search堆栈溢出,它可能是一个“跨域问题”,因此我应该添加一些JavaScript到我宁静的web服务:

 var express = require('express'), wine = require('./routes/wines'); var app = express(); app.configure(function () { app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */ app.use(express.bodyParser()); //Added part app.all('/', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "*"); res.header("Access-Control-Allow-Methods", "XPOST, GET, OPTIONS"); res.header("Access-Control-Max-Age", "1000"); next(); }); //Added part }); app.get('/wines', wine.findAll); app.get('/wines/:id', wine.findById); app.post('/wines', wine.addWine); app.put('/wines/:id', wine.updateWine); app.delete('/wines/:id', wine.deleteWine); app.listen(1337); console.log('Listening on port 1337...'); 

仍然没有结果,任何人一个想法如何解决这个问题? 很多thanx

您必须在调用open()之前注册事件处理程序。

 var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (this.status == 200 && this.readyState == 4) { console.log('response: ' + this.responseText); alert("Yes"); } }; xhr.open('GET', 'http://localhost:1337/wines/'); xhr.send();