在MEAN堆栈

时间:2018-05-13 20:54:21

标签: node.js express

我正在研究我的第一个平均堆栈应用程序并遇到问题。我有一个Blog模型,我正在尝试从req对象中分配属性,但它没有完成。当我执行req.body的控制台日志时,它看起来像这样:

{ '{"title":"some title", "body":"some body", "createdBy":" "created By"}':''}

但是当我单独记录值时,如console.log(req.body.title)未定义。在我的server.js中,我已经包含了body解析器,并确保路由是在合并body解析器之后。所以在这一点上我不确定为什么它会被定义为任何帮助。

这是博客的帖子:

  createAuthenticationHeaders() {
this.authService.loadToken();
this.httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/x-www-form-urlencoded',
    authorization: this.authService.authToken
  })
};

}

newBlog(blog) {    
  this.createAuthenticationHeaders(); // Create headers
  return this.http.post(this.domain + 'blogs/newBlog', blog, 
   this.httpOptions);
}

这是有效载荷 enter image description here

由于

这是该文件

const express = require('express');
const app = express();
const router = express.Router();
const mongoose = require('mongoose');
const config = require('./config/database');
const path = require('path');
const authentication = require('./routes/authentication')(router);
const blogs = require('./routes/blogs')(router);
const bodyParser = require('body-parser');
const cors = require('cors');
const port = 8080;

mongoose.connect(config.uri, err => {
   if (err) {
      console.log('Connection error db ', err);
   } else {
      console.log('Connected to db ', config.db);
    }
   });


  app.use(
    cors({
     origin: 'http://localhost:4200'
    })
  );

  app.use(bodyParser.urlencoded({ extended: false }));

  app.use(bodyParser.json());

  app.use(express.static(__dirname + '/client/dist/'));
  app.use('/authentication', authentication);
  app.use('/blogs', blogs);

   app.get('*', (req, res) => res.sendFile(__dirname + 
      '/client/dist/index.html'));
   app.listen(port, () => console.log(`App listening on port ${port}`));

1 个答案:

答案 0 :(得分:0)

  

当我执行req.body的控制台日志时,它看起来像这样:

{ '{"title":"some title", "body":"some body", "createdBy":" "created By"}':''}

您发布了一个JSON,它有另一个JSON作为属性,因此req.body.title未定义。检查您的客户端,因为您发布的JSON错误。

// This is what you say you're getting
const bad = { '{"title":"some title", "body":"some body", "createdBy":" "created By"}':''};

console.log(bad);
console.log(bad.title);

// This is what you should post
const good = {"title":"some title", "body":"some body", "createdBy":"created By"};

console.log(good);
console.log(good.title);

更新

您正在发送表单数据,而不是JSON有效负载。

使用:'Content-Type': 'application/json'代替'Content-Type': 'application/x-www-form-urlencoded'