2013-01-06 15 views
2

用途:
1)創建一個在NodeJs Web服務器上運行的網站。 (expressjs,手寫筆,玉器)+的NodeJS
2)上的NodeJS web服務器創建一個RESTful Web服務 (expressjs)+的NodeJS
3)該網站調用一個RESTful Web服務進入 (JavaScript文件)使用javascript調用expressjs restful webservice =>結果始終爲空respons


隨着ubuntu的終端i開始的NodeJS爲網站的另一個用於其餘 webservice.Testing的寧靜web服務(在瀏覽器):

地址:本地主機:1337 /葡萄酒/

數據結果是: [ { 「名」: 「新酒」, 「年」: 「2012」, 「_id」: 「50e8255197f0b5260f000001」 } ]

測試網站 網址:localhost:3000/

這是我在網站中使用的javascript文件,在這裏我想打電話給 rest 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(); 

在我看到的GET進行端子:
雷斯特夫爾終端:
GET /葡萄酒/ 200的3ms - 93

網站終端:
GET/200 11毫秒
GET /JavaScript/script.js 304毫秒
GET /stylesheets/style.css 304毫秒

當調試IG oes是這樣的:
var xhr = new XMLHttpRequest(); OK
xhr.open('GET','http:// localhost:1337/wines /');好
xhr.send(); OK

xhr.onreadystatechange =()函數跳進回電確定
而是 '的readyState = 4,但this.status = 0',我不給一個結果

最終我得到這個錯誤:
組件返回故障代碼:0x80004005的(NS_ERROR_FAILURE)從螢火蟲(用於調試該Java腳本)


結果信息

Content-Type application/json;字符集= UTF-8
日期星期日,2013年1月6日4時15分07秒GMT
X供電,通過快遞
請求頭
接受text/html的,是application/xhtml + xml的,應用/ XML; Q = 0.9,/; q = 0。8
接受編碼gzip的,放氣
接受語言EN-US,EN; Q = 0.5
連接保持
主機本地主機:1337
產地//本地主機:3000
的Referer //本地主機: 3000/
用戶代理的Mozilla/5.0(X11; Ubuntu的版本; Linux x86_64的; RV:13.0)壁虎/ 20100101
火狐/ 13.0.1


我搜索堆棧溢出和它可能是一個「跨域問題',因此我應該 添加索姆ËJavaScript來我的RESTful 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...'); 

Still no result, anyone an idea how to fix this issue? Many thanx

回答

0

你必須調用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(); 
+0

對於響應的Thx,我試過但得到相同的錯誤,調試信息:跳轉到函數()status = 0,readystate = 0 |打開|發送|跳轉到函數()狀態= 0,readystate = 4(相同的錯誤) –

相關問題