- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我不想从 301.json 获取重定向,而是想向我的 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();
}
}
最佳答案
要建立在@Dominooch 的答案之上,如果您只想返回 JSON,则可以使用 .json() 帮助器。它会自动将内容类型设置为 application/json 并将您传递给它的对象字符串化。
为了阐明我们在这里做什么,我们将完全替换您的 301.json
并使用 nuxt 的创建中间件的方式来:
如果 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' },
]
}
// 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
}
关于vue.js - Nuxt serverMiddleware 从 API 获取 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52904480/
新的 nuxt.js 设置不附带服务器文件夹 您创建一个 API 文件夹并在其中放置一个公开服务器的文件 我正在尝试使用 ws 来使用 websockets解析用户 session 并收到此错误的库
新的 nuxt.js 设置不附带服务器文件夹 您创建一个 API 文件夹并在其中放置一个公开服务器的文件 我正在尝试使用 ws 来使用 websockets解析用户 session 并收到此错误的库
想法 首先,您有一个与其他网站一样的主要 Nuxt 网站。然后将我的模块添加到您的项目中。然后,我的模块将一个子域“admin.example.com”添加到您的项目中,这是一个完全充实的基于 Nux
我不想从 301.json 获取重定向,而是想向我的 api 发出一个返回我的 json 的请求。 我正在使用 @nuxtjs/axios 模块。 const redirects = require(
我目前正在构建一个 Vue/Nuxt 应用程序,并结合修改后的 Saleor 安装来在线销售产品。 当我们从现有系统迁移时,我们需要能够处理从旧网站 URL 到新网站 URL 的 301 重定向。 我
我目前正在构建一个 Vue/Nuxt 应用程序,并结合修改后的 Saleor 安装来在线销售产品。 当我们从现有系统迁移时,我们需要能够处理从旧网站 URL 到新网站 URL 的 301 重定向。 我
我是一名优秀的程序员,十分优秀!