我创建了一个简单的nodejs项目作为后端服务器。当我尝试消费" http://localhost:3000/users"在我的Angular 6项目中,我总是遇到http响应错误。但是,如果我使用json服务器作为后端服务器来提供相同的API,它就可以工作。我用我的浏览器和Postman测试过,我很确定nodejs Express服务器和json服务器提供完全相同的内容。谁能帮我解决这个问题?非常感谢!
我的nodejs app.js代码,
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.route('/users').get((req, res) => {
res.send(
[
{
"id": "5b03d4dd1a193d0ab08b1af8",
"username": "bwteksuper",
"level": 3,
"is_active": true,
"created_date": "2018-05-22T08:29:17.200000Z"
},
{
"id": "5b03d4f81a193d0ab08b1af9",
"username": "jade",
"level": 2,
"is_active": true,
"created_date": "2018-05-22T08:29:44.492000Z"
}
]
);
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
我的json服务器db.json,
{
"users": [
{
"id": "5b03d4dd1a193d0ab08b1af8",
"username": "bwteksuper",
"level": 3,
"is_active": true,
"created_date": "2018-05-22T08:29:17.200000Z"
},
{
"id": "5b03d4f81a193d0ab08b1af9",
"username": "jade",
"level": 2,
"is_active": true,
"created_date": "2018-05-22T08:29:44.492000Z"
}
]
}
我的角色代码,
export class UserService {
constructor(private http: HttpClient) { }
getUsers(): Observable<User[]>{
return this.http.get<User[]>('http://localhost:3000/users');
}
}
export class UsersComponent implements OnInit {
users: User[];
constructor(private userService: UserService) {}
ngOnInit() {
this.userService
.getUsers()
.subscribe(data => {this.users = data;});
}
}
Http响应错误,
HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false, …}
core.js:1598
error:ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, …}
headers:HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
message:"Http failure response for (unknown url): 0 Unknown Error"
name:"HttpErrorResponse"
ok:false
status:0
statusText:"Unknown Error"
url:null
__proto__:HttpResponseBase {constructor: }
答案 0 :(得分:0)
你可以试试像
这样的东西EXPRESS
var express = require('express');
var router = express.Router();
// Hello.
router.get('/', function (req, res) {
res.send('Hello');
})
// User page route.
router.get('/users', function (req, res) {
res.send(/* USER JSON HERE */);
})
app.use('/api', router);
角
getUsers(): Observable<User[]>{
return this.http.get<User[]>('api/users') // Without http://3000
答案 1 :(得分:0)
只需在nodejs项目中启用CORS即可解决此问题。