如何解决本地 GET 请求不同于 Heroku 部署的请求
我正在尝试部署我的第一个 MERN 堆栈应用程序。我遵循了此处链接的教程系列 https://www.youtube.com/watch?v=qyomEaXQJFk&t=121s
我很挣扎,因为我的整个应用程序崩溃了,我认为这是授权 GET 请求的问题。
router.get('/user',auth,async (req,res) => {
try {
const user = await User.findById(req.user.id).select('-password');
console.log(user);
if (!user) throw Error('User does not exist');
res.json(user);
} catch (e) {
res.status(400).json({ msg: e.message });
}
});
以上是我的GET请求,在http://localhost:5000/api/auth/user获取
function auth(req,res,next) {
const token = req.header('x-auth-token');
if(!token) {res.status(401).json({msg: 'No token,authorization denied'});
console.log("help");
}
try {
const decoded = jwt.verify(token,config.get('jwtSecret'));
req.user = decoded;
next();
} catch(e) {
res.status(400).json({ msg: 'Token is not valid'});
}
}
以上是我验证令牌并允许执行 GET 请求的中间件。
当我通过邮递员请求本地主机时,它返回:
{
"msg": "Token is not valid"
}
这是我想要的功能。但是,当我的网站部署在 https://pacific-crag-38763.herokuapp.com/ 邮递员返回
<!doctype html>
<html lang="en">
<head>
<Meta charset="utf-8" />
<link rel="icon" href="/favicon.ico" />
<Meta name="viewport" content="width=device-width,initial-scale=1" />
<Meta name="theme-color" content="#000000" />
<Meta name="description" content="Web site created using create-react-app" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css"
integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous" />
<link rel="manifest" href="/manifest.json" />
<title>Musify</title>
<link href="/static/css/main.e195e564.chunk.css" rel="stylesheet">
</head>...
它继续返回我的整个 index.html 文档。我不知道为什么会发生这种情况,也不知道它在哪里获取 index.html。我的理论是,当我部署到 Heroku 时,我必须将它添加到我的 server.js
if(process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname,"client","build")))
app.get('*',(req,res) => {
res.sendFile(path.join(__dirname+'/client/build/index.html'));
});
}
所以也许它以某种方式将我的 index.html 从我的构建文件夹发送到我的 GET 请求?我是这一切的新手,因此我们将不胜感激。
解决方法
如果有人为此挣扎,我补充
if(process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname,"client","build")))
app.get('*',(req,res) => {
res.sendFile(path.join(__dirname+'/client/build/index.html'));
});
}
在我之前
app.use('/api/users',require('./routes/api/user'));
app.use('/api/auth',require('./routes/api/auth'));
这导致每个 GET 请求都返回构建 index.html。将 if 语句移到我的路线下方解决了问题。
在这上面花了几个小时。
FML
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。