2

目的:
1)创建一个在 NodeJs 网络服务器上运行的网站。(expressjs、stylus、jade)+NodeJS
2)在NodeJs webserver上创建一个restful webservice(expressjs)+NodeJS
3)网站调用一个restful web service入口(javascript文件)


使用 ubuntu 终端,我为网站启动 nodeJs,为其余 webservice 启动另一个 nodeJs。测试 restful webservice(在浏览器中):

网址:localhost:1337/wines/

数据结果为: [ { "name": "New wine", "Year": "2012", "_id": "50e8255197f0b5260f000001" } ]

测试网站Url:localhost:3000/

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

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:
Restful 终端:
GET /wines/ 200 3ms - 93

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

当我调试时,我是这样的:
var xhr = new XMLHttpRequest(); 好的
xhr.open('GET', 'http://localhost:1337/wines/'); 好的
xhr.send(); 好的

xhr.onreadystatechange = function () 跳转到回调 OK
but 'readystate=4 but this.status = 0' 而且我没有给出结果

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


来自 firebug 的结果信息(用于调试此 java 脚本)

内容类型应用程序/json;charset=utf-8
日期 Sun, 06 Jan 2013 04:15:07 GMT
X-Powered-By Express
Request Headers
Accept text/html,application/xhtml+xml,application/xml;q=0.9, / ;q=0.8
Accept -Encoding gzip, deflate
Accept-Language en-us,en;q=0.5
Connection keep-alive
Host localhost:1337
Origin //localhost:3000
Referer //localhost:3000/
User-Agent Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:13.0) Gecko/20100101
Firefox/13.0.1


我搜索了堆栈溢出,它可能是一个“跨域问题”,因此我应该在我的 restful 网络服务中添加一些 javascript:

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...');

仍然没有结果,有人知道如何解决这个问题吗?多谢

4

1 回答 1

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();
于 2013-01-06T05:11:10.340 回答