Nodejs 应用程序抛出不能 POST /users with body-parser 中间件

Nodejs app throws cannot POST /users with body-parser middleware

这是我的 app.js 文件。

    var  express = require('express'),
     bodyParser = require('body-parser'),
     oauthServer = require('oauth2-server'),
     oauth_model = require('./app_modules/oauth_model')


const app = express()

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

var jsonParser = bodyParser.json();

app.oauth = oauthServer({
  model: oauth_model, // See below for specification 
  grants: ['password', 'refresh_token'],
  debug: process.env.OAUTH_DEBUG,
  accessTokenLifetime: 172800,
  refreshTokenLifetime: 172800,
  authCodeLifetime: 120,


});


// Oauth endpoint.

app.all('/oauth/token', app.oauth.grant());


//  User registration endpoint.

app.post('/users', jsonParser, require('./routes/register.js'));


// Get user details.

app.get('/users', app.oauth.authorise(), require('./routes/users.js'));


app.post('/', app.oauth.authorise(), require('./routes/test.js'));

app.use(app.oauth.errorHandler());



app.listen(3000, function () {
  console.log('Mixtra app listening on port 3000!')
})

当我向 localhost:3000/users 发送带有 POST 请求的无效 json 正文时,请求转到 register.js 并且验证码在那里工作。

但奇怪的是,当我发送有效的 JSON 正文时,它说 "Cannot POST /users" 带有 404 Not Found HTTP 状态代码,并且终端日志中没有任何内容。

注意:我正在使用邮递员发送 api 请求。

如果有人能帮助我,那就太好了。

谢谢,

欢乐

我没看到你在使用 jsonParser

你应该在发送任何 json 之前使用它

app.use(jsonParser);