req.body返回undefined?

时间:2018-02-20 01:07:00

标签: javascript node.js express body-parser

我已经通过npm安装了body解析器,需要它,设置它使用express buti am仍然得到req.body undefined。如果有人知道什么是错的,请让我知道我觉得它是一个愚蠢的东西我失踪了。 这是我的app.js文件

const express = require('express')
const index = require('./routes/index');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');

//Create the express server
const app = express();

// Use index routes file
app.use('', index);

// Use the /public folder for our assets
app.use('/public', express.static('public'));

// Use body-parser and cookie-parser
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(cookieParser);

// Set ejs as our templating engine
app.set('view engine', 'ejs');

// Catch 404 and forward to error handler
app.use(function(req, res, next) {
  const err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// Error handler
app.use((err, req, res, next) => {
  res.locals.message = err.message;
  res.status(res.statusCode || 500);
  res.render('error', {error: err.message});
  console.log(err.message);
});

app.listen(process.env.PORT || 3000, () => {
    console.log('Application running on localhost:3000');

});

这是我的路线index.js文件正在发布

const express = require('express');
const router = express.Router();
const fs = require('fs');
const movie_controller = require('../controllers/movieController');
const bodyParser = require('body-parser');
const request = require('request');

router.get('/about', (req, res, error) => {
    res.render('about');
});

router.get('/', movie_controller.get_index);
router.get('/currently_playing', movie_controller.get_currently_playing);
router.get('/top_rated', movie_controller.get_top_rated);
router.get('/upcoming', movie_controller.get_upcoming);
router.get('/movie_view/:id', movie_controller.get_movie);
// Post request for a search query
router.post('/search', (req, res, next) => {

    console.log('Query', req.body);

    // Make request for query
    request('https://api.themoviedb.org/3/search/movie?api_key=&language=en-
US&query=' + req.body + '&page=1&include_adult=false', (error, response, 
body) => {

        //handle errors
        if(error){res.render('error', {error: error.message})}

        //handle body
        if(response.statusCode === 200){

            //place body data in a variable for later reference
             let movieData = JSON.parse(body);
             let movies = [];

            movieData.results.forEach(movie => {
                 movies.push(movie);
            });

            // Make request for genres
            request('https://api.themoviedb.org/3/genre/movie/list?
api_key=&language=en-US', (error, response, body) => {

                //handle errors
                if(error){res.render('error', {error: error.message})}

                //handle body
                if(response.statusCode === 200){

                    //place body in a variable for later reference
                    let genreData = JSON.parse(body);
                    let genres = [];

                    genreData.genres.forEach(genre => {
                        genres.push(genre);
                    });


                    res.render('results', {movie: movies, genres: genres });

                }


            })
        }

    })

});




module.exports = router;

这是表单在header.ejs partial

上的位置
<form class="form-inline my-2 my-lg-0" action="/search" method="post">
    <input class="form-control mr-sm-2" type="search" placeholder="Search" name="searchQuery" aria-label="Search">
    <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>enter code here

2 个答案:

答案 0 :(得分:0)

Express中间件按照您注册的顺序运行(包括路由)。在附加路线后,您已注册了bodyParsercookieParser中间件。因此,在遇到路由时,您将不会拥有已解析的正文或Cookie。

要解决此问题,请确保在实际路由之前要运行的任何中间件都已注册:

const express = require('express')
const index = require('./routes/index');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');

//Create the express server
const app = express();

// Use the /public folder for our assets
app.use('/public', express.static('public'));

// Use body-parser and cookie-parser
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(cookieParser);

// Use index routes file
app.use('', index);

...

答案 1 :(得分:0)

您应该在路由器app.use('', index)之前使用app.use('', index),以避免出现任何问题,只需将// Use body-parser and cookie-parser app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.json()); app.use(cookieParser); // Use index routes file app.use('', index); 放在最后。


npm install @types/node @types/express -D