Try to search your question here, if you can't find : Ask Any Question Now ?

invalid csrf token when using ajax

HomeCategory: stackoverflowinvalid csrf token when using ajax
Avatarbhawya asked 3 months ago

I started learning NodeJs and pushed by my knowledge of js I start writing some code for create the user registration logic.

Essentially I have configured ExpressJS in the following way:

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const session = require('express-session');
const csrf = require('csurf');
const cookieParser = require('cookie-parser');

    secret: 'foofofoo',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: true }

app.use(bodyParser.urlencoded({ extended: false }));
app.use(function (req, res, next) {
    var csrfToken = req.csrfToken();
    res.cookie('XSRF-TOKEN', csrfToken);
    res.locals.csrfToken = csrfToken;

then I created a basic .ejs view for the user registration:

<meta name="csrf-token" content="<%= csrfToken %>">
    <label class="w3-text-blue"><b>User Name</b></label>
    <input class="w3-input w3-border" id="uname" name="uname" type="text"></p>
    <label class="w3-text-blue"><b>Password</b></label>
    <input class="w3-input w3-border" id="upass" name="pass" type="text"></p>
    <button class="w3-btn w3-blue" id="regForm">Register</button></p>

the csrfToken is taken by the middleware above.
When the user press the button regForm this code is called:

$("#regForm").click(function () {
    let uname = $("#uname").val();
    let upass = $("#upass").val();
    let token  = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
    let regData = 
        'name': uname, 
        'pass': upass 

        type: 'POST',
        url: '/registerUser',
        headers: {"X-CSRF-Token": token },
        data: regData,
        success: function (data) {

and looking at the ajax request the token is passed correctly:

enter image description here

but inside the console I get:

ForbiddenError: invalid csrf token

this is the route method:'/registerUser', function(req, res, next){
1 Answers
Best Answer
AvatarFernando answered 3 months ago
Your Answer

5 + 0 =

Popular Tags

WP Facebook Auto Publish Powered By :