我是MEAN堆栈的新手我希望从快递服务器(我用mongodb创建)中获取数据,当我点击按钮时,按钮点击功能被执行但请求未完成,数据库,服务器全部运行好吧,我在控制台什么都没有,这是我的客户端和服务器文件:
客户端(在http://localhost:3001上运行)
导入的模块并添加到ngModule中的导入
从“@ angular / http”导入{Http,Headers,HttpModule,Response,RequestOptions};
在构造函数中作为服务注入,然后: 模板:
<button md-button class="button1" (click)="newQues()">Submit</button>
课堂上:
newQues(){
this.http.get('https://localhost:3000/')
.map(this.extractData)
.catch(this.handleError); //these copied from angular2
//official documentation
}
private extractData(res: Response) {
let body = res.json();
console.log(body); //not getting console nor error
return body.data || { };
}
服务器在端口3000上运行
app.get('/', function (req, res) {
model.findOne({ id: 1}, function (err, data) {
if (err) {
console.log(err)
} else {
console.log(data);
res.send(data);
}
})
整个服务器代码:
import * as express from "express";
var app = express();
import * as path from "path";
import * as mongoose from "mongoose";
import * as lodash from "lodash";
import * as morgan from "morgan";
app.use(express.static(path.join(__dirname, "./../client")));
var uriString = 'mongodb://localhost/quizapp';
mongoose.connect(uriString, function (err, res) {
if (err) {
console.log("Error occured while establishing connection " + err);
} else {
console.log("Connection successful ");
}
})
var schema = new mongoose.Schema({ //schema
question: String,
id: Number
})
var quizz = mongoose.model('Quiz', schema); //creating model
var firstDoc = new quizz({
question: 'question 1',
id: 1
})
var secondDoc = new quizz({
question: 'question 2',
id: 2
})
var question_data = [firstDoc, secondDoc];
quizz.insertMany(question_data, function (err, res) {
if (err) {
console.log("Error occured while saving document object " + err)
} else {
console.log("Data Saved Successful");
}
})
app.get('/data', function(req, res) {
quizz.findOne({ id: 1}, function (err, data) {
if (err) {
console.log(err)
} else {
console.log(data);
res.send(data); //res.json
}
})
})
当我路由到localhost时:3000 / data来自数据库的数据显示在窗口上,但是当从客户端请求该路由时(请参阅客户端代码this.http.get)发生错误(附图)
答案 0 :(得分:0)
用于提取您必须订阅的数据。试试这种方式
export class SimpleHTTPComponent {
data: Object;
loading: boolean;
constructor(public http: Http) {
}
makeRequest(): void {
this.loading = true;
this.http.request('http://jsonplaceholder.typicode.com/posts/1')
.subscribe((res: Response) => {
this.data = res.json();
this.loading = false;
});
}
}
我认为您没有将this
与body
一起使用。你的console.log应该是这样的。 console.log(this.body);