我面临与此类似的尾部斜杠问题如何删除 gatsby 项目中的尾部斜杠?。 当我尝试重新加载一秒钟时,它会加载带有尾部斜杠的网址,例如 website.com/page1/,然后返回 website.com/page1。它发生在我在 gatsby-node.js 中创建的那些上。我尝试过删除尾部斜杠插件但没有得到结果
如果有任何帮助,我将不胜感激。谢谢你。
这是我的 gatsby-node.js 的样子
const path = require(`path`)
const { slash } = require(`gatsby-core-utils`)
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions
// query content for WordPress posts
const {
data: {
allWpLandingPage: { nodes: allLandingPages },
allWpPost: { nodes: allPosts },
},
} = await graphql(`
query {
allWpLandingPage {
nodes {
id,
slug,
landing_page{
baseFolder
}
}
}
allWpPost {
nodes {
categories {
nodes {
slug
}
}
blogPostInfo {
adressForUrl
img {
mediaItemUrl
altText
}
}
author{
node{
name
}
}
content
id
title
}
}
}
`)
const postTemplate = path.resolve(`./src/pages/landing.js`);
allLandingPages.forEach(post => {
let title = post.landing_page.baseFolder.toLowerCase().replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"").split(' ').join('-');
post.uri = title + '/' + post.slug;
createPage({
// will be the url for the page
//path: post.slug,
path: '/' + post.uri ,
// specify the component template of your choice
component: slash(postTemplate),
// In the ^template's GraphQL query, 'id' will be available
// as a GraphQL variable to query for this post's data.
context: {
id: post.id,
},
})
})
let filteredPosts = allPosts.filter((item) => {
for (let i = 0; i < item.categories.nodes.length; i++){
if (item.categories.nodes[i].slug === "blog-posts"){
return item;
}
}
});
const blogPostTemplate = path.resolve(`./src/pages/article-page.js`);
filteredPosts.forEach(post => {
createPage({
path: 'blog/' + post.blogPostInfo.adressForUrl,
component: slash(blogPostTemplate),
context: {
id: post.id,
},
})
})
}
您是否尝试过删除
slug
创建中的尾部斜杠?
createPage({
path: '/' + post.uri.replace(/\/$/, ""),
component: slash(postTemplate),
context: {
id: post.id,
},
})
replace(/\/$/, "")
正则表达式应该可以解决问题
自从
[email protected]
以来,就有了删除尾部斜杠的选项。这是有关它的文档https://www.gatsbyjs.com/docs/reference/config-files/gatsby-config/#trailingslash
我希望这有帮助。
在 gatsby-config.js 文件中添加以下属性解决了我在 Gatsby 项目中删除末尾或 URL 处的斜杠的问题。
// gatsby-config.js
trailingSlash: "never"