我正在尝试通过nextJS提供一些静态文件,特别是sitemap.xml和robots.txt。我曾尝试从服务器提供文件并在客户端访问我的静态文件夹,但这些文件均未显示在浏览器中。我是否缺少阻止这些文件加载到浏览器中的功能?
这是我的服务器/src/index.js
const cookieParser = require('cookie-parser')
const jwt = require('jsonwebtoken')
require('dotenv').config({path: '.env'})
const createServer = require('./createServer')
const db = require('./db')
const path = require('path');
const server = createServer()
//Express middleware to handle cookies
server.express.use(cookieParser())
//decode JWT
server.express.use((req, res, next) => {
const { token } = req.cookies;
if (token) {
const { userId } = jwt.verify(token, process.env.APP_SECRET);
req.userId = userId;
}
next()
})
//Populates user on request
server.express.use(async (req, res, next) => {
if(!req.userId) return next()
const user = await db.query.user({
where: {id: req.userId}
}, `{id, permissions, email, name}`)
req.user = user
next()
})
//start
server.start({
cors: {
credentials: true,
origin: process.env.FRONTEND_URL
},
}, starting => {
console.log(`server is running on port ${starting.port}`)
})
const sitemapOptions = {
root: path.join(__dirname, '/client/static'),
headers: {
'Content-Type': 'text/xml;charset=UTF-8',
}
};
server.get('/sitemap.xml', (req, res) => {
return res.status(200).sendFile('sitemap.xml', sitemapOptions)
})
和server / src / createServer.js文件
const {GraphQLServer} = require('graphql-yoga')
const Mutation = require('./resolvers/Mutation')
const Query = require('./resolvers/Query')
const db = require('./db')
//GraphQL Yoga server
function createServer() {
return new GraphQLServer({
typeDefs: 'src/schema.graphql',
resolvers: {
Mutation,
Query
},
resolverValidationOptions: {
requireResolversForResolveType: false
},
context: req => ({...req, db})
})
}
module.exports = createServer