mongodb - 我无法使用 angular 2 发布到我的 mongodb 服务器

标签 mongodb http post angular

您好,我在向我的 mongodb 数据库发帖时遇到问题。我似乎无法向我的 server.js 发帖。我尝试使用 ngmodel 将我的表单连接到我的帖子,但它指出找不到我的 call_post。但我不确定这是否是唯一的问题。有人能指出我正确的方向吗?谢谢你

服务器.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;

应用程序组件.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.
    );
  }
}

演示.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())
    );
  }

}

最佳答案

试着改变这个:

应用程序组件.ts:

public call= this.call_post;

doPost() {
    this._demoService.post(this.call);
}

为此:

public call_post;

doPost() {
  this._demoService.post(this.call_post);
}

关于mongodb - 我无法使用 angular 2 发布到我的 mongodb 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37645507/

相关文章:

php - 无法使用Fuel Kotlin将POST请求发送到我的PHP页面

java - 为什么 MongoDB Java API 的更新插入如此慢?

objective-c - objective-c - 通过 http POST 发送图像

JavaScript 远程事件?

ios - iOS 中的大型 Base64 上传

php - JavaScript 表单提交不发送输入类型的值=提交

ASP.NET MS11-100 : how can I change the limit on the maximum number of posted form values?

python - 查找速度 : State or Database?

node.js - POST 到 AWS EC2 Mongodb 数据库在生产中不起作用

node.js - Mongoose 聚合与 geonear