简体   繁体   English

出现错误:未捕获(承诺):状态为404的URL找不到响应:

[英]Getting Error: Uncaught (in promise): Response with status: 404 Not Found for URL:

I am making a request to endpoint written in koa.js and I am new to this framework. 我正在向以koa.js编写的终结点发出请求,而我是这个框架的新手。 API return 404 response. API返回404响应。

Route file looks like below: 路由文件如下所示:

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)
}

when I log rest.post(FEED_API + '/follow', args) I get: 当我登录rest.post(FEED_API +'/ follow',args)时,我得到:

Promise { _bitField: 0, _fulfillmentHandler0: undefined, 承诺{_bitField:0,_fulfillmentHandler0:未定义,
_rejectionHandler0: undefined, _progressHandler0: undefined, _promise0: undefined, _receiver0: undefined, _settledValue: undefined } Unhandled rejection Error: Cannot POST http://localhost/activity-feed/api/v1/follow at Request. _rejectionHandler0:未定义,_progressHandler0:未定义,_promise0:未定义,_receiver0:未定义,_settledValue:未定义}未处理的拒绝错误:无法在请求时发布POST http:// localhost / activity-feed / api / v1 / (\\node_modules\\restling\\restling.js:26:21) at Request.emit (events.js:180:13) at Request._fireSuccess (\\node_modules\\restler\\lib\\restler.js:223:12) at \\node_modules\\restler\\lib\\restler.js:161:20 at IncomingMessage.auto (\\node_modules\\restler\\lib\\restler.js:402:7) at Request._encode (\\node_modules\\restler\\lib\\restler.js:198:29) at \\node_modules\\restler\\lib\\restler.js:157:16 at Request._decode (\\node_modules\\restler\\lib\\restler.js:173:7) at IncomingMessage. (\\ node_modules \\ restling \\ restling.js:26:21)在Request.emit(events.js:180:13)在Request._fireSuccess(\\ node_modules \\ restler \\ lib \\ restler.js:223:12)在\\ node_modules在IncomingMessage.auto上的\\ restler \\ lib \\ restler.js:161:20(\\ node_modules \\ restler \\ lib \\ restler.js:402:7)在Request._encode(\\ node_modules \\ restler \\ lib \\ restler.js:198: 29)在Request._decode处的\\ node_modules \\ restler \\ lib \\ restler.js:157:16(在IncomingMessage处的Request._decode(\\ node_modules \\ restler \\ lib \\ restler.js:173:7)中。 (\\node_modules\\restler\\lib\\restler.js:150:14) at IncomingMessage.emit (events.js:185:15) at endReadableNT (_stream_readable.js:1106:12) at process._tickCallback (internal/process/next_tick.js:178:19) (\\ node_modules \\ restler \\ lib \\ restler.js:150:14)位于process .. .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

I have removed extra code which is not relevant to this question. 我删除了与该问题无关的多余代码。

Functions called within route: 路由内调用的函数:

Function 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)
}

Function follow 功能跟随

 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]
            })
    },

请求

Can someone help me and tell me what is wrong with my code? 有人可以帮助我,告诉我代码有什么问题吗? I am signed in and session has JWT, route exist then why I am getting 404? 我已登录并且会话具有JWT,路由存在,那么为什么我会得到404? What is wrong with code at backend? 后端代码有什么问题?

In browser console I get: 在浏览器控制台中,我得到:

Error: Uncaught (in promise): Response with status: 404 Not Found for URL 错误:未捕获(承诺):状态为404的URL找不到响应

This is what I get when I print console.log(rest.post(FEED_API + '/follow', args)) 这是我打印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)

Update 更新资料

Below is activity feed route: 以下是活动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
        })
})

Function called inside this route 此路线内部调用的函数

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
},

app.js of activity-feed/api 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

Any help would be highly appreciated! 任何帮助将不胜感激!

While registering the routes you have missed the FEED_API (base url). 在注册路线时,您错过了FEED_API(基本URL)。

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

So your url actually looks like http://localhost/collab/follow instead of http://localhost/activity-feed/api/v1/follow 因此,您的网址实际上看起来像http:// localhost / collab / follow,而不是http:// localhost / activity-feed / api / v1 / follow

Instead, you should register your routes like, 相反,您应该注册路线,例如

// 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) {

Now you can POST to /collab/follow as http://localhost/activity-feed/api/v1/collab/follow 现在您可以以http:// localhost / activity-feed / api / v1 / collab / follow的身份发布到/ collab / follow

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 获取错误响应,状态为:URL找不到404 - Getting error Response with status: 404 Not Found for URL 是什么导致“错误:未捕获(承诺):Url:null 的状态为 200 的响应”显示? - What cause “Error: Uncaught (in promise): Response with status:200 for Url:null” to show up? 为什么我收到此错误未捕获(承诺)错误:请求失败,状态码为 404,我的 api 在 postman 中正常,但是当我在前面尝试时我 Z34D1F91FB2E514B8576FAB1A75ABZer8 - why i am getting this error Uncaught (in promise) Error: Request failed with status code 404, my api is ok in postman, but when i try in front i go er 当我将数据提交到数据库表时,我在浏览器控制台中遇到此错误:未捕获(承诺)错误:请求失败,状态代码为 404 - While I go to submit data into Database table I face this error in browser console: Uncaught (in promise) Error: Request failed with status code 404 我收到 Uncaught (in promise) 错误:请求失败,状态码为 401 - I am getting Uncaught (in promise) Error: Request failed with status code 401 未捕获(承诺):状态响应:Angular2 / Ionic2中的0 - Uncaught (in promise): Response with status: 0 in Angular2/Ionic2 错误“POST http://localhost:3000/api/auth/createuser(与 /api/auth/login 路径相同)404(未找到)”和“未在 Promise 中捕获:语法错误” - Error "POST http://localhost:3000/api/auth/createuser (same with /api/auth/login path) 404 (Not Found)" & "Uncaught in Promise: Syntax Error" 我收到错误 Vue warn]: Error in v-on handler (Promise/async): "Error: Request failed with status code 404" - I am getting the error Vue warn]: Error in v-on handler (Promise/async): "Error: Request failed with status code 404" Axios - 未捕获(承诺)错误:请求失败,状态码为 500 - Axios - Uncaught (in promise) Error: Request failed with status code 500 未捕获(承诺)错误:请求失败,状态码为500 - Uncaught (in promise) Error: Request failed with status code 500
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM