TypeError:无法解构“ req.body”的属性“ userId”,因为它未定义

时间:2020-06-18 17:18:27

标签: javascript mysql node.js postman

每次我尝试在邮递员中向 http://localhost:3000/api/orders/new

发出发帖请求

我收到此错误: ** TypeError:无法解构“ req.body”的属性“ userId”,因为它未定义。 在C:\ Users \ Web-Developer \ Desktop \ shoppy \ backend \ routes \ orders.js:70:10 在Layer.handle上[作为handle_request](C:\ Users \ Web-Developer \ Desktop \ shoppy \ backend \ node_modules \ express \ lib \ router \ layer.js:95:5) 在下一个(C:\ Users \ Web-Developer \ Desktop \ shoppy \ backend \ node_modules \ express \ lib \ router \ route.js:137:13) 在Route.dispatch(C:\ Users \ Web-Developer \ Desktop \ shoppy \ backend \ node_modules \ express \ lib \ router \ route.js:112:3) 在Layer.handle上[作为handle_request](C:\ Users \ Web-Developer \ Desktop \ shoppy \ backend \ node_modules \ express \ lib \ router \ layer.js:95:5) 在C:\ Users \ Web-Developer \ Desktop \ shoppy \ backend \ node_modules \ express \ lib \ router \ index.js:281:22 在Function.process_params(C:\ Users \ Web-Developer \ Desktop \ shoppy \ backend \ node_modules \ express \ lib \ router \ index.js:335:12) 在下一个(C:\ Users \ Web-Developer \ Desktop \ shoppy \ backend \ node_modules \ express \ lib \ router \ index.js:275:10) 在Function.handle(C:\ Users \ Web-Developer \ Desktop \ shoppy \ backend \ node_modules \ express \ lib \ router \ index.js:174:3) 在路由器上(C:\ Users \ Web-Developer \ Desktop \ shoppy \ backend \ node_modules \ express \ lib \ router \ index.js:47:12) **

const router = express.Router();
const {database} = require('../config/helpers');

/* GET ALL ORDERS */
router.get('/', (req, res) => {
    database.table('orders_details as od')
        .join([
            {
                table: 'orders as o',
                on: 'o.id = od.order_id'
            },
            {
                table: 'products as p',
                on: 'p.id = od.product_id'
            },
            {
                table: 'users as u',
                on: 'u.id = o.user_id'
            }
        ])
        .withFields(['o.id', 'p.title as name', 'p.description', 'p.price', 'u.username'])
        .sort({id: 1})
        .getAll()
        .then(orders => {
            if(orders.length > 0) {
                res.status(200).json(orders);
            } else {
                res.json({message: 'Mo Orders Found'})
            }
        }).catch(err => console.log(err));
})


/* GET SINGLE ORDER */
router.get('/:id', (req, res) => {

    const orderId = req.params.id;

    database.table('orders_details as od')
        .join([
            {
                table: 'orders as o',
                on: 'o.id = od.order_id'
            },
            {
                table: 'products as p',
                on: 'p.id = od.product_id'
            },
            {
                table: 'users as u',
                on: 'u.id = o.user_id'
            }
        ])
        .withFields(['o.id', 'p.title as name', 'p.description', 'p.price', 'u.username'])
        .filter({'o.id': orderId})
        .getAll()
        .then(orders => {
            if(orders.length > 0) {
                res.status(200).json(orders);
            } else {
                res.json({message: `No Orders Found with orderId ${orderId}`})
            }
        }).catch(err => console.log(err));
})

/* PLACE A NEW ORDER */
router.post('/new', (req, res) => {

    let {userId, products} = req.body;
    console.log(userId, products)
})

module.exports = router

5 个答案:

答案 0 :(得分:6)

const { google } = require('googleapis')
const scopes = [
  'https://www.googleapis.com/auth/spreadsheets.readonly',
  'https://www.googleapis.com/auth/userinfo.email',
  'https://www.googleapis.com/auth/drive.readonly'
]

module.exports = (env, mongo) => {
  const getBaseClient = () => {
    const { OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET, OAUTH_CALLBACK_URL } = env.credentials
    return new google.auth.OAuth2(
      OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET, OAUTH_CALLBACK_URL
    )
  }

  const getNewAccessTokens = async (authId, refreshToken) => {
    const { tokens } = await getBaseClient().getToken(refreshToken)
    await mongo.setAccessTokensForAuthUser(authId, { ...tokens, refresh_token: refreshToken })
    return tokens
  }

  const getAuthedClient = async (authId) => {
    let tokens = await mongo.getAccessTokensForAuthUser(authId)

    if (!tokens.access_token) {
      tokens = await getNewAccessTokens(authId, tokens.refresh_token)
    }

    const client = getBaseClient()
    client.setCredentials(tokens)

    if (client.isTokenExpiring()) {
      const { credentials } = await client.refreshAccessToken()
      tokens = { ...credentials, refresh_token: tokens.refreshToken }
      await mongo.setAccessTokensForAuthUser(authId, tokens)
      client.setCredentials(tokens)
    }

    return client
  }

  const generateAuthUrl = (userId) => {
    return getBaseClient().generateAuthUrl({
      access_type: 'offline',
      scope: scopes,
      state: `userId=${userId}`
    })
  }

  const getUserInfo = async (authId) => {
    const auth = await getAuthedClient(authId)
    return google.oauth2({ version: 'v2', auth }).userinfo.get({})
  }

  const listSheets = async (authId) => {
    const auth = await getAuthedClient(authId)
    let nextPageToken = null
    let results = []
    do {
      const { data } = await google
        .drive({ version: 'v3', auth })
        .files.list({
          q: 'mimeType = \'application/vnd.google-apps.spreadsheet\'',
          includeItemsFromAllDrives: true,
          supportsAllDrives: true,
          corpora: 'user',
          orderBy: 'name',
          pageToken: nextPageToken
        })
      nextPageToken = data.nextPageToken
      results = results.concat(data.files)
    } while (nextPageToken)
    return results
  }

  return {
    generateAuthUrl,
    getUserInfo,
    listSheets
  }
}

我发现在指定路由路径之前需要使用此代码。

答案 1 :(得分:2)

这是解决方案...是的!

不需要安装body-parser。

尝试一下:

app.use(express.json())

并在诸如以下路线之前指定它:

(顺序在这里确实很重要!)

app.use(express.json());
app.use('/api', Anyroute)

答案 2 :(得分:1)

您可能缺少bodyParser

const bodyParser = require('body-parser')

app.use(bodyParser.json()) // for parsing application/json

答案 3 :(得分:1)

确保将数据作为原始 JSON 传递,如下图所示。

enter image description here

答案 4 :(得分:0)

我在server.ts中拥有

app.use('/admin', adminRoutes);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }))

给出了错误信息。更改为

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }))
app.use('/admin', adminRoutes);

使其起作用。就像OP在评论中所说的那样,顺序必须首先是正文解析器,然后是路由路径。