未定义的请求无法读取属性' push'未定义的

时间:2018-06-16 14:12:21

标签: node.js api express body-parser

我想在服务器上发布数据,但我无法这样做。我收到错误:

  

无法读取属性'推送'未定义的

我正在使用body-parser。未定义的object.am我在StudentRoute.js文件中导入引用正确的方法,我检查App.js中的post方法哪里正常工作,但是在studentRoute.js文件中post方法无效。

StudentRoute.js文件

import express from 'express'; 
var app = express();
import bodyParser from 'body-parser';
// var bodyParser = require('body-parser');
import students from '../data/students.json';

const router=express.Router();


let studentsArray=students;


router.get('/:id',(req,res)=>{      //like here replace '/:id'
    const studnet=_.find(studentsArray,studnet=>studnet.id==req.params.id);
    if(studnet){
        res.json(studnet);
    }
    else
    {
         res.send(`User with id:${req.params.id} not found`);
    }

});

router.get('/',(req,res)=>{
    res.json(studentsArray)
    res.end();
}); 
router.post('/',(req,res)=>{
    console.log("post request");
    console.log(req.body);
    students.studentsArray.push(req.body);
    res.status(200).send("OK");
});   
router.put('/',(req,res)=>{
    console.log("put request") 
    res.end();
});
router.delete('/',(req,res)=>{
    console.log("Delete request")
    res.end();
    });

router.param('id',(req,res,next,id)=>{
        if(isNaN(id)){
            next(`${id} Not a number`);
        }
        next();
    });    

 module.exports=router;   

其他文件APP.js

import express from 'express';
import students from './data/students.json';
import StudentRoute from './routes/StudentRoute';
import _ from 'lodash';
import morgan from 'morgan';
import bodyParser from 'body-parser';
import https from 'https';
const port=3000;

const buildurl=(version,path)=>`/api/${version}/${path}`; 
const STUDENT_BASE_URL=buildurl('v1','students');

const server=express();

server.use(morgan('tiny'));
server.use(STUDENT_BASE_URL,StudentRoute);

server.use(bodyParser.json({ type: 'application/*+json' }));
server.use(bodyParser.json());

server.listen(3000, () => {
    console.log(`server started on port ${port}`);

});

0 个答案:

没有答案