簡體   English   中英

Node.js-TypeError:res.json不是一個函數(在某些路由中有效,而在其他路由中無效)

[英]Node.js - TypeError: res.json is not a function (working in some routes and not in others)

在MERN堆棧(Mongo,Express,React,Node)中工作,並在我的API中遇到錯誤。

這是我的plaid.js文件,其中我的一條路由plaid.js此錯誤。 當然,我已經刪除了所有秘密令牌變量,但假定一切正常,直到res.json錯誤(確實如此)。

        const express = require("express");
        const plaid = require("plaid");
        const router = express.Router();
        const jwt = require("jsonwebtoken");
        const keys = require("../../config/keys");
        const passport = require("passport");
        const moment = require("moment");
        const mongoose = require("mongoose");

        // Load Account and User models
        const Account = require("../../models/Account");
        const User = require("../../models/User");

        // Replaced my actual keys with empty strings for sake of this post
        const PLAID_CLIENT_ID = "";
        const PLAID_SECRET = "";
        const PLAID_PUBLIC_KEY = "";

        const client = new plaid.Client(
          PLAID_CLIENT_ID,
          PLAID_SECRET,
          PLAID_PUBLIC_KEY,
          plaid.environments.sandbox,
          { version: "2018-05-22" }
        );

        var PUBLIC_TOKEN = null;
        var ACCESS_TOKEN = null;
        var ITEM_ID = null;

        // @route POST api/plaid/accounts/add
        // @desc Trades public token for access token and stores credentials in database
        // @access Private
        router.post(
          "/accounts/add",
          passport.authenticate("jwt", { session: false }),
          (req, res) => {
            PUBLIC_TOKEN = req.body.public_token;

            const userId = req.user.id;
            const institution = req.body.metadata.institution;
            const { name, institution_id } = institution;

            if (PUBLIC_TOKEN) {
              client
                .exchangePublicToken(PUBLIC_TOKEN)
                .then(res => {
                  ACCESS_TOKEN = res.access_token;
                  ITEM_ID = res.item_id;

                  // Check if account already exists for specific user
                  Account.findOne({
                    userId: req.user.id,
                    institutionId: institution_id
                  })
                    .then(account => {
                      if (account) {
                        console.log("Account already exists");
                      } else {
                        const newAccount = new Account({
                          userId: userId,
                          publicToken: PUBLIC_TOKEN,
                          accessToken: ACCESS_TOKEN,
                          itemId: ITEM_ID,
                          institutionId: institution_id,
                          institutionName: name
                        });

                        // TO:DO fix error, res.json is not a function
                        newAccount.save().then(account => res.json(account));
                      }
                    })
                    .catch(err => console.log(err)); // Mongo Error
                })
                .catch(err => console.log(err)); // Plaid Error
            }
          }
        );
    module.exports = router;

newAccount.save()執行得很好,但是隨后的res.json拋出錯誤。 這是我得到返回的錯誤。 即, res.json is not a function

[0] (node:23413) UnhandledPromiseRejectionWarning: TypeError: res.json is not a function
[0]     at newAccount.save.then.account (/Users/rishi/plaid-auth/routes/api/plaid.js:97:55)
[0]     at process._tickCallback (internal/process/next_tick.js:68:7)

res.json is not a function上有很多帖子res.json is not a function錯誤,但是沒有提出的解決方案對我res.json is not a function 我很困惑為什么會引發此錯誤,因為我在應用程序的另一部分中使用了相同的約定,並且res.json正常工作。 請參見下面的res.json工作位置res.json

// @route POST api/posts
// @desc Create a post
// @access Private
router.post(
  "/",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    const { errors, isValid } = validatePostInput(req.body);

    // Check validation
    if (!isValid) {
      return res.status(400).json(errors);
    }

    const newPost = new Post({
      text: req.body.text,
      name: req.body.name,
      avatar: req.body.avatar,
      user: req.user.id // current logged in user
    });

    // res.json works just fine
    newPost.save().then(post => res.json(post));
  }
);

這是因為這段代碼

if (PUBLIC_TOKEN) {
          client
            .exchangePublicToken(PUBLIC_TOKEN)
            .then(res => {
              ACCESS_TOKEN = res.access_token;

當您執行此行時, newAccount.save().then(account => res.json(account)); res不再是功能router.post('/accounts/add', (req, res) => {})

因此,解決方案很簡單,將資源從promise exchangePublicToken更改為其他示例,例如下面的示例。

您正在將promise回調中的參數命名為與router.post上的回調中的參數相同

if (PUBLIC_TOKEN) {
          client
            .exchangePublicToken(PUBLIC_TOKEN)
            .then(exchangeResponse => {
              ACCESS_TOKEN = exchangeResponse.access_token;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM