【问题标题】:POST request contains no 'body' field with Satellizer, Express and google authPOST 请求不包含带有 Satellizer、Express 和 google auth 的“正文”字段
【发布时间】:2018-07-17 22:28:02
【问题描述】:

我正在使用包含 NodeJS/Express 背面和 AngularJS 正面的 Satellizer 开发我的第一个应用程序。我希望我的用户使用他们的 Google 帐户登录。

前端位于 8000 端口,我已将其配置为:

app.config(function($authProvider) {
  $authProvider.google({
    url: 'http://localhost:3000/auth/google',
    clientId: 'id.apps.googleusercontent.com',
  })
});

对于后面(端口 3000),我遵循了 github repo 示例。 here

app.post('/auth/google', function(req, res) {
  var accessTokenUrl = 'https://accounts.google.com/o/oauth2/token';
  var peopleApiUrl = 'https://www.googleapis.com/plus/v1/people/me/openIdConnect';
  var params = {
    code: req.body.code,
    client_id: req.body.clientId,
    client_secret: config.GOOGLE_SECRET,
    redirect_uri: req.body.redirectUri,
    grant_type: 'authorization_code'
 };
 ...

当我点击“登录”按钮时,弹出窗口,我可以使用我的凭据并关闭它。但是我没有登录,后面有错误: 'TypeError: 无法读取未定义的属性'code'。'

一个console.log()后发现问题是req.body为空。这就是我卡住的地方。我错过了一步吗?

这里是发送到 Express 的请求:

[1531831850948] 选项 /auth/google

[1531831851007] POST /auth/google

我也启用了 CORS

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

【问题讨论】:

    标签: node.js satellizer


    【解决方案1】:

    缺少上下文,但我猜你需要一个正文解析器中间件。

    查看body-parser (link),然后在您的应用中像这样使用它:

    const express = require('express')
    const bodyParser = require('body-parser')
    
    const app = express()
    
    // parse application/x-www-form-urlencoded
    app.use(bodyParser.urlencoded({ extended: false }))
    
    // parse application/json
    app.use(bodyParser.json())
    
    app.use(function (req, res) {
      res.end('you posted:\n' + JSON.stringify(req.body, null, 2))
    })
    

    此示例将发回 post 有效负载。

    【讨论】:

    • @Moulissse 很高兴我能帮上忙。 :)
    猜你喜欢
    • 2014-08-09
    • 2020-12-23
    • 2019-03-24
    • 2018-08-22
    • 2022-01-17
    • 2013-05-30
    • 1970-01-01
    • 2023-03-21
    • 2019-06-26
    相关资源
    最近更新 更多