【问题标题】:Nuxt serverMiddleware get json from APINuxt serverMiddleware 从 API 获取 json
【发布时间】:2019-03-25 01:27:36
【问题描述】:

我不想从 301.json 获取重定向,而是想向我的 api 发出请求,该 api 返回我的 json。

我正在使用@nuxtjs/axios 模块。

const redirects = require('../301.json');

export default function (req, res, next) {

    const redirect = redirects.find(r => r.from === req.url);

    if (redirect) {
        console.log('redirect: ${redirect.from} => ${redirect.to}');
        res.writeHead(301, { Location: redirect.to });
        res.end();
    } else {
        next();
    }
}

【问题讨论】:

  • 你试过什么?什么没用?

标签: vue.js vuejs2 axios nuxt.js


【解决方案1】:

原答案

要基于@Dominooch 的答案,如果您只想返回 JSON,您可以使用 .json() 帮助程序。它会自动将 content-type 设置为 application/json 并且 stringify 是你传递给它的一个对象。

编辑:

为了澄清我们在这里所做的事情,我们将完全替换您的 301.json 并使用 nuxt 创建中间件的方式来:

  1. 定义一个通用处理程序,您可以将其重用于任何路由
  2. 明确定义哪些路径将使用您的处理程序(我假设您是 301.json 正在做的事情)

如果 301.json 真的只是您想要重定向的路径数组,那么您可以使用 .map() 但我个人不会,因为目前还不清楚哪些路径被重定向(请参阅我的最后一个示例) 也就是说,我要避免的最后一件事是制作一个全局中间件(为每个请求触发),以检查路径是否包含在您的数组中。 .map() 将使 nuxt 为您进行路由匹配(无论如何它已经这样做了),而不是通过您的处理程序发送 每个 请求。

// some-api-endpoint.js
import axios from 'axios'

export default {
    path: '/endpoint'
    handler: async (req, res) => {
        const { data } = await axios.get('some-request')
        res.json(data)
    }
}

然后在你的 nuxt.config.js 中:

// nuxt.config.js

module.exports = {
    // some other exported properties ...
    serverMiddleware: [
        { path: '/endpoint', handler: '~/path/to/some-api-endpoint.js' },
    ]
}

如果 301.json 真的只是一个路径数组:

// nuxt.config.js

const routes = require('../301.json');

module.exports = {
    // some other exported properties ...
    serverMiddleware: routes.map(path =>
        ({ path, handler: '~/path/to/some-api-endpoint.js' }))
}

或者如果你有其他中间件:

// nuxt.config.js

const routes = require('../301.json');

module.exports = {
  // some other exported properties ...
  serverMiddleware: [
    ...routes.map(path =>
      ({ path, handler: '~/path/to/some-api-endpoint.js' })),
    ... // Other middlewares
}

【讨论】:

  • 虽然此代码可能会解决问题,including an explanation 关于如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的回答添加解释并说明适用的限制和假设。
【解决方案2】:

这是我所做的,它似乎有效:

//uri-path.js
import axios from 'axios'

export default {
  path: '/uri/path',
  async handler (req, res) {
    const { data } = await axios.get('http://127.0.0.1:8000/uri/path')
    res.setHeader('Content-Type', 'text/html')
    res.end(data)
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-30
    • 2021-04-07
    • 1970-01-01
    • 2020-06-17
    • 2020-12-12
    • 2019-10-07
    • 2020-10-30
    • 2021-03-07
    相关资源
    最近更新 更多