繁体   English   中英

Koa-Router:如果请求不在 XHR 中,则跳过路由

[英]Koa-Router : Skip the route if the request not in XHR

我有一个用 Koa 制作的 Rest API和一些路由,但同时,它将为我的 Front 服务(由 JS 框架和它自己的路由器制作)。

The fact is, when I access from a browser "localhost/user" I want to display the front but when I reach the same url from fetch / ajax / XMLHttpRequest I want to display a JSON result (the one gave by the Koa-router )。

所以我想启用来自 API 的 /user 路由,前提是它是从 XHR 调用的。

我做了这样的 isXMLHttpRequest 中间件:

module.exports = async (ctx, next) => {
    if(ctx.request.get('X-Requested-With') === 'XMLHttpRequest') {
        return next()
    }
}

然后,在我的 koa-router 中,我做了类似的事情:

const Router = require('koa-router')

const isXMLHttpRequest = require("@middlewares/isXMLHttpRequest")

const router = new Router()

const user = require("@routes/user")
router.use('/user', isXMLHttpRequest, user.routes(), user.allowedMethods())

然后,当我执行一些 XHR 请求时,它可以工作,我按计划拥有 JSON,但是如果我尝试从浏览器访问 /user,API 给了我一个未找到的错误,而不是我的前面......

我正在寻找如何跳过路由器。如果请求不是在 XHR 中发出的,请使用 function,但我找不到解决方案......

我认为这是在中间件的其他情况下,我必须返回一些东西,但是我该怎么做才能跳过 koa-router 给我 404 ......

也许你能帮助我?

不确定我的问题是否正确。 所以你有一个像 static web 服务器和 REST ZDB974238714CA8DE6347A,对吗?

我会尝试反过来做。 使用例如 koa-static ( https://www.npmjs.com/package/koa-static )将首先尝试提供您的文件,如果在您定义的公共目录中找不到匹配的文件,则所有其他路线(所以您的 REST API ) 被处理。 然后您只需确保端点名称不会与您正在服务的文件重叠。

好的,所以如果您对 static 和 XMLHttpRequests 使用相同的路由(这可能不是最好的策略),那么这可能会起作用:

const Koa = require('koa')
const Router = require('koa-router')

const app = module.exports = new Koa();

isXmlRequest = (ctx) => {
    // here you could also compare e.g. "accept" header
    return (ctx.request.header && ctx.request.header['x-requested-with'] === 'XMLHttpRequest');
}

// static routes
const staticRouter = new Router()
staticRouter.get('/user', (ctx, next) => {
    ctx.body = 'OK from static route';
    next();
});

// XMLHttpRequest routes
const xmlRouter = new Router()
xmlRouter.get('/user', (ctx, next) => {
    if (isXmlRequest(ctx)) {
        // serve it
        ctx.body = { ok: 'from JSON/XML' }
    } else {
        // downstream to next handler
        next();
    }
});

app.use(xmlRouter.routes());
app.use(staticRouter.routes());

const server = app.listen(3000)

这不是使用中间件 bw因为在这里你只能允许下游使用next但如果没有 next 则停止。 没有else了 ;-) 仅供参考

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM