您好我发布到我的mongodb数据库时遇到了问题。我似乎无法向我的server.js发布任何内容。我尝试使用ngmodel将我的表单连接到我的帖子,但它声明我的call_post无法找到。我不确定这是否是唯一的问题。有人能指出我正确的方向。谢谢
server.js
var express = require('express'),
app= express(),
engines = require('consolidate'),
MongoClient = require('mongodb').MongoClient,
assert = require('assert');
bodyParser = require('body-parser');
var app = express();
app.engine('html', engines.nunjucks);
app.set('view engine', 'html');
app.use(express.static(__dirname + '/'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// view engine setup
// catch 404 and forward to error handler
MongoClient.connect('mongodb://localhost:27017/munchies', function(err, db){
assert.equal(null, err);
console.log("Successfully connected to MongoDB.");
app.get('/', function(req, res){
res.render('index.html' );
});
app.get('/name', function(req, res){
db.collection('names').find().toArray(function(err, docs) {
if (!err) {
console.log(docs);
res.json(docs);
}
else{
console.log(err);
}
})
});
app.post('/calls', function(req, res) {
console.log("Post body.value is "+ req.body.value)
req.assert('value', 'An integer >= 0 is required').isInt()
if (req.body.value < 0) {
console.log("invalid integer (less than zero)")
res.status(400).send('Invalid integer')
}
get_counter = parseInt(req.body.value, 10);
console.log("get_counter" + get_counter)
res.status(200)
});
app.use(function(req, res){
res.sendStatus(404);
});
var server = app.listen(3000, function() {
var port=server.address().port;
console.log('express server listening on port %s', port);
});
});
module.exports = app;
app.component.ts
import {DemoService} from './demo.service';
import {Component} from 'angular2/core';
import {FORM_DIRECTIVES} from "angular2/common";
import {HTTP_PROVIDERS} from 'angular2/http';
@Component({
selector: 'demo-app',
template:`
<h1>Angular2 HTTP Demo App</h1>
<form f="postForm" (ngSubmit)="doPost()">
<button type="submit" class="btn btn-warning btn-lg">POST</button>
<input [(ngModel)]="call_post" placeholder="0">
</form>
<h2>Foods</h2>
<ul>
<li *ngFor="#food of foods">{{food.name}}</li>
</ul>
<h2>Books and Movies</h2>
<h3>Books</h3>
<ul>
<li *ngFor="#book of books">{{book.title}}</li>
</ul>
<h3>Movies</h3>
<ul>
<li *ngFor="#movie of movies">{{movie.title}}</li>
</ul>
`,
})
export class AppComponent {
public foods;
public books;
public movies;
public call= this.call_post;
constructor(private _demoService: DemoService) { }
ngOnInit() {
this.getFoods();
this.getBooksAndMovies();
this.doPost();
}
doPost() {
this._demoService.post(this.call);
}
getFoods() {
this._demoService.getFoods().subscribe(
// the first argument is a function which runs on success
data => { this.foods = data},
// the second argument is a function which runs on error
err => console.error(err),
// the third argument is a function which runs on completion
() => console.log('done loading foods')
);
}
getBooksAndMovies() {
this._demoService.getBooksAndMovies().subscribe(
data => {
this.books = data[0]
this.movies = data[1]
}
// No error or completion callbacks here. They are optional, but
// you will get console errors if the Observable is in an error state.
);
}
}
demo.services.ts
import {Http, Headers, URLSearchParams, Response} from 'angular2/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map'; // lib is large, add only the map operator as result
import {RequestOptions} from "angular2/http";
import {Component, enableProdMode, Injectable} from 'angular2/core';
@Injectable()
export class DemoService {
constructor(private http:Http) { }
post(value) {
console.log('in the post? ' + JSON.stringify(value))
const endpoint = 'http://localhost:3000//calls';
const headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
var body = JSON.stringify({"value": value});
return this.http.post(endpoint, body, options)
.map((res: Response) => res.json()).subscribe()
}
// Uses http.get() to load a single JSON file
getFoods() {
return this.http.get('/name').map((res:Response) => res.json());
}
// Uses Observable.forkJoin() to run multiple concurrent http.get() requests.
// The entire operation will result in an error state if any single request fails.
getBooksAndMovies() {
return Observable.forkJoin(
this.http.get('/app/books.json').map((res:Response) => res.json()),
this.http.get('/app/movies.json').map((res:Response) => res.json())
);
}
}
答案 0 :(得分:0)
尝试改变这一点:
app.component.ts:
public call= this.call_post;
doPost() {
this._demoService.post(this.call);
}
到此:
public call_post;
doPost() {
this._demoService.post(this.call_post);
}