获取错误:未捕获(在承诺中):状态响应:找不到404的URL:

时间:2018-05-07 12:51:44

标签: node.js async-await http-status-code-404 koa koa.js

我正在向koa.js写的端点发出请求,我是这个框架的新手。 API返回404响应。

路线文件如下所示:

const collabRepo = require("../repo/collab/collab-repo")
const notificationRepo = require("../repo/collab/notification-repo")
const rest = require("restling")
const jwt = require("jsonwebtoken")
const CONFIG = require("config")
const SECRET = CONFIG.get("auth.jwt.secret")
const JWT_COOKIE_NAME = CONFIG.get("auth.jwt.cookie.name")
const TOKENTIME = CONFIG.get("auth.jwt.ttl")
const FEED_API_BASE = CONFIG.get("urls.activityFeedApi")
const FEED_API_VERSION = "v1"
const FEED_API = FEED_API_BASE + "/" + FEED_API_VERSION
const logger = require("winston")
const { jwtAuth } = require("../auth")

const PROTECTED_ROUTES = [
    "/collab/follow",
    "/collab/unfollow",
    "/collab/follower/list",
    "/collab/follower/public/list",
    "/collab/following/list",
    "/collab/following/public/list",
    "/collab/following/count",
    "/collab/following",
    "/collab/notify",
    "/collab/discover/people",
    "/collab/discover/expression"
]

async function followFeed(toFollowId, userObject, follow) {
    const args = {
        data: {
            follow: {
                class: "user",
                id: toFollowId
            }
        },
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "Cookie": JWT_COOKIE_NAME + "=" + jwt.sign(userObject, SECRET, {
                expiresIn: TOKENTIME
            })
        }
    }
    if (follow) {
        return rest.post(FEED_API + '/follow', args)
    }
    return rest.post(FEED_API + '/unfollow', args)
}

当我记录rest.post(FEED_API +' / follow',args)时,我得到:

  

承诺{_bitField:0,_fulfillmentHandler0:undefined,
  _rejectionHandler0:undefined,_progressHandler0:undefined,_promise0:undefined,_receiver0:undefined,_ settledValue:undefined}未处理的拒绝错误:无法POST   http://localhost/activity-feed/api/v1/follow       在请求。 (\ node_modules \ restling \ restling.js:26:21)       在Request.emit(events.js:180:13)       在Request._fireSuccess(\ node_modules \ restler \ lib \ restler.js:223:12)       at \ node_modules \ restler \ lib \ restler.js:161:20       在IncomingMessage.auto(\ node_modules \ restler \ lib \ restler.js:402:7)       在Request._encode(\ node_modules \ restler \ lib \ restler.js:198:29)       at \ node_modules \ restler \ lib \ restler.js:157:16       在Request._decode(\ node_modules \ restler \ lib \ restler.js:173:7)       在IncomingMessage。 (\ node_modules \ restler \ lib中\ restler.js:150:14)       在IncomingMessage.emit(events.js:185:15)       at endReadableNT(_stream_readable.js:1106:12)       at process._tickCallback(internal / process / next_tick.js:178:19)

module.exports = (router) => {
    // Protect the marked routes
    PROTECTED_ROUTES.forEach(url => {
        router.use(url, jwtAuth)
    })
    // router.use("/collab", jwtAuth)

    router.post("/collab/follow", async function (ctx) {
        try {
            const resp = await followFeed(ctx.request.body.followee_id, ctx.state.user, true)
            return collabRepo.follow(ctx.state.user.id, ctx.request.body.followee_type, ctx.request.body.followee_id)
                .then(data => {
                    ctx.body = {
                        data: data,
                        feed_data: resp.data
                    }
                })
        } catch (error) {
            return error
        }
    }),

} // end of the module

我删除了与此问题无关的额外代码。

在路线中调用的函数:

功能followFeed

async function followFeed(toFollowId, userObject, follow) {
    const args = {
        data: {
            follow: {
                class: "user",
                id: toFollowId
            }
        },
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "Cookie": JWT_COOKIE_NAME + "=" + jwt.sign(userObject, SECRET, {
                expiresIn: TOKENTIME
            })
        }
    }
    if (follow) {
        return rest.post(FEED_API + '/follow', args)
    }
    return rest.post(FEED_API + '/unfollow', args)
}

功能跟随

 follow: function(user_id, followee_type, followee_id) {
        return db("follower").returning("followee_id").insert({ "user_id": user_id, "followee_id": followee_id, "followee_type": followee_type })
            .then(data => {
                return data[0]
            })
    },

Request

有人可以帮助我并告诉我我的代码有什么问题吗? 我登录并且会话有JWT,路由存在然后为什么我得到404? 后端的代码有什么问题?

在浏览器控制台中,我得到:

  

错误:未捕获(在承诺中):状态响应:404 Not Found for   URL

这是我打印console.log(rest.post(FEED_API + '/follow', args))

时得到的结果
Promise {
  _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _progressHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined,
  _settledValue: undefined }
Unhandled rejection Error: Cannot POST http://localhost/activity-feed/api/v1/follow
    at Request.<anonymous> (projectpath\node_modules\restling\restling.js:26:21)

更新

以下是活动Feed路径:

router.post("/v1/follow", function(ctx) {
    const user = ctx.state.user
    const request = ctx.request.body
    return feedRepo.followUserFeed(user.id, request.follow)
        .then(result => {
            ctx.body = result
        })
        .catch(error => {
            ctx.error = error
        })
})

在此路线内召唤的功能

followUserFeed: async function(id, feed) {
    const userFeed = new GSFlatFeed(LOOKUP.FEEDS.USER, id)
    const feedToFollow = new GSFlatFeed(feed.class, feed.id)
    const res = await StreamProvider.followFeed(userFeed, feedToFollow)
    return res
},

activity-feed / api的app.js

const Koa = require("koa")
const Router = require("koa-router")
const body = require("koa-body")
const cors = require("kcors")
const passport = require("koa-passport")
const logger = require("winston")
var JwtStrategy = require("passport-jwt").Strategy
const CONFIG = require("config")
const SECRET = CONFIG.get("auth.jwt.secret")
const JWT_COOKIE_NAME = CONFIG.get("auth.jwt.cookie.name")

const allRoutes = require("./server/routes/all-routes")

const app = new Koa()
const router = new Router()
const jwtAuth = passport.authenticate(["jwt"], { session: false })

passport.use(new JwtStrategy({
        secretOrKey: SECRET,
        jwtFromRequest: function(req) {
            var token = null
            if (req && req.cookies) {
                token = req.cookies.get(JWT_COOKIE_NAME)
            }
            return token
        }
    },
    function(jwt_payload, done) {
        done(null, jwt_payload)
    }))

router.use("/v1/*", jwtAuth)

allRoutes(router)

app.use(async(ctx, next) => {
    try {
        await next()
    } catch (err) {
        logger.error(err)
        ctx.throw(err.status || 500, err.message)
    }
})
app.use(cors())
app.use(passport.initialize())
app.use(body())
app
    .use(router.routes())
    .use(router.allowedMethods())

module.exports = app

任何帮助都将受到高度赞赏!

1 个答案:

答案 0 :(得分:0)

在注册路线时,您错过了FEED_API(基本网址)。

PROTECTED_ROUTES.forEach(url => {
   router.use(url, jwtAuth)
})

因此,您的网址实际上看起来像 http://localhost/collab/follow 而不是http://localhost/activity-feed/api/v1/follow

相反,您应该注册您的路线,如

// Protect the marked routes
module.exports = (router) => {
   // Protect the marked routes
   PROTECTED_ROUTES.forEach(url => {
       router.use(FEED_API  + url, jwtAuth)
   })
   // router.use("/collab", jwtAuth)

   router.post(FEED_API + "/collab/follow", async function (ctx) {

现在您可以以http://localhost/activity-feed/api/v1/collab/follow

的身份发布到/ collab / follow