Answer the question
In order to leave comments, you need to log in
How to send cookies with fetch and fix 404 post error?
Hello. I'm trying to send a post to a server that uses a jwt token for authorization, but I get a post 404.
Here is the logic for setting the token and the user:
app.use((req, res, next)=>{
const jwtToken = req.cookies.JWT_TOKEN;
if(!jwtToken) {
next();
return;
}
jwt.verify(jwtToken, SECRET, (err, decoded)=>{
if(err) {
next(err);
return;
}
const sessionData = decoded.data;
let userId;
if (sessionData['modx.user.contextTokens']) {
if (sessionData['modx.user.contextTokens']['web'] > 0) {
userId = sessionData['modx.user.contextTokens']['web'];
}else if($dataarr['modx.user.contextTokens']['mgr'] > 0) {
userId = sessionData['modx.user.contextTokens']['mgr'];
}else {
return res.redirect('/signin');
}
}
req.user = {userId};
next();
});
});
app.use((req, res, next)=>{
if (!req.user || !req.user.userId) {
next(new Error('Access Denied'));
}else {
next();
}
});
app.get("/:id?", function(req, res){
const room = {id:parseInt(req.params.id||0)};
const userid = req.user.userId;
console.log('USEEEEEEEEEEEEEEEEEEEEEEEEEER ID', userid);
pool.query("SELECT * FROM modx_user_attributes WHERE id = ?", [userid], function(err, [userData]) {
if(err) return console.log(err);
//console.log('userData ', userData);
const token = jwt.sign({
data: {userId: userid},
}, SECRET);
res.render("index.hbs", {
appdata: {token, room, user: userData},
finalScripts,
});
});
});
app.post('/writeVideo', (req, res) => {
req.video.mv('test.wav', (err) => {
if (err) {
res.send(err);
} else {
res.send({
success: 'file write'
})
}
});
})
fetch('/writeVideo', {
method: 'POST',
credentials: "same-origin",
headers: {
'Content-type': 'application/json',
},
body: {
user: {
userId: 8
},
video: audioBlob
}
}).then(data => data.json()).then(data => console.log(data));
Answer the question
In order to leave comments, you need to log in
If you analyze how this ingenious design works for you:
if (!req.user || !req.user.userId) {
then perhaps you will get an answer to your question
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question