我的前端是 Reactjs,后端是 Nodejs 和 expressjs 以及 Postgresql 数据库。我有一个简单的登录页面,用于检查数据库中的用户身份验证。在我的 Reactjs 应用程序中,登录后,用户上传文件,然后我的 nodejs 上有一个 GET 方法,当用户想要从服务器获取文件时发送文件(res.sendFile)。这只是一个简单的
<img alt='none' src=`http://example.com/source/${filename}` />
在我的 Reactjs 应用程序中请求文件。
问题:如果我没有登录到我的应用程序,我可以将 URL 粘贴到我的浏览器中,并且显示的文件不是我想要的。我希望nodejs上的GET方法应该检查用户是否登录,然后只满足发送文件的请求。
我该怎么做?
在我的 Reactjs 应用程序向 GET 方法的同一位置发出任何 GET 请求之前,我是否应该在我的 Reactjs 应用程序中使用某种 POST 方法,然后解析信息,然后将其处理到 app.get 等...
这是我的 nodejs + expressjs。
服务器.js
app.post('/signin', (req, res) => { signin.handleSignin(req, res, db, bcrypt)})
app.get('/source/:fileid', (req, res) => {
const { fileid } = req.params;
res.sendFile(__dirname + /data/ + fileid);
});
./controllers/signin.js
const handleSignin = (req, res, db, bcrypt) => {
const { email, password } = req.body;
if (!email || !password ) {
return res.status(400).json('Incorrect form submission');
}
db.select('email', 'hash').from('login')
.where('email', '=', email)
.then(data => {
const isValid = bcrypt.compareSync(password, data[0].hash);
if (isValid) {
return db.select('*').from('users')
.where('email', '=', email)
.then(user => {
res.json(user[0])
})
.catch(err => res.status(400).json('unable to get user'))
} else {
res.status(400).json('wrong credentials' )
}
})
.catch(err => res.status(400).json('wrong credentials'))
}
module.exports = {
handleSignin: handleSignin
}