Home > Software engineering >  node js empty request
node js empty request

Time:04-12

Everything worked for me until I added csrf. I use in public/js/editor.js fetch to send the image file to the server:

fetch('/upload', {
    method: 'post',
    body: formdata
}).then(res => res.json())
.then(data => {
    if (uploadType == 'image')
    {
        addImage(data, file.name);
    }
    else if (uploadType == 'banner')
    {
        bannerPath = `${location.origin}/${data}`;
        banner.style.backgroundImage = `url("${bannerPath}")`
    }
    else
    {
        console.error('Данный тип файла не поддерживается');
    }
})

In the server.js I accept the file:

app.post('/upload', (req, res) => {
    console.log(req.files);
    
    let file = req.files.image;
    let date = new Date();
    console.log('test post');
    // image name
    let imagename = date.getDate()   date.getTime()   file.name;
    // image upload path
    let path = 'public/uploads/'   imagename;

    // create upload
    file.mv(path, (err, result) => {
        if (err) {
            throw err;
        } else {
            // our image upload path
            res.json(`uploads/${imagename}`)
        }
    })
})

After adding csrf files began to look like this:

Become:

editor.js FULL

const csrfToken = getCookie('XSRF-TOKEN');
console.log(csrfToken);
const headers = new Headers({
    'Content-Type': 'x-www-form-urlencoded',
    'X-CSRF-Token': csrfToken
});

fetch('/upload', {
    method: 'post',
    headers: headers,
    credentials: 'include',
    body: formdata
}).then(res => res.json())
.then(data => {
    if (uploadType == 'image')
    {
        addImage(data, file.name);
    }
    else if (uploadType == 'banner')
    {
        bannerPath = `${location.origin}/${data}`;
        banner.style.backgroundImage = `url("${bannerPath}")`
    }
    else
    {
        console.error('Данный тип файла не поддерживается');
    }
})

function getCookie(name) {
    if (!document.cookie) {
      return null;
    }
  
    const xsrfCookies = document.cookie.split(';')
      .map(c => c.trim())
      .filter(c => c.startsWith(name   '='));
  
    if (xsrfCookies.length === 0) {
      return null;
    }
    return decodeURIComponent(xsrfCookies[0].split('=')[1]);
  }

and server.js FULL

const cookieParser = require("cookie-parser");
const csrf = require("csurf");

const csrfMiddleware = csrf({ cookie: true });
app.use(cookieParser());
app.use(csrfMiddleware);

app.all("*", (req, res, next) => {
    var token = req.csrfToken();
    res.cookie("XSRF-TOKEN", token);
    res.locals.csrfToken = token;
    next();
});

app.use(function (req, res, next) {
    var token = req.csrfToken();
    res.cookie('XSRF-TOKEN', token);
    res.locals.csrfToken = token;
    next();
});

//upload link
app.post('/upload', (req, res) => {
    console.log(req.files);
    
    let file = req.files.image;
    let date = new Date();
    console.log('test post');
    // image name
    let imagename = date.getDate()   date.getTime()   file.name;
    // image upload path
    let path = 'public/uploads/'   imagename;

    // create upload
    file.mv(path, (err, result) => {
        if (err) {
            throw err;
        } else {
            // our image upload path
            res.json(`uploads/${imagename}`)
        }
    })
})

Problem

But now after uploading the image to editor.js , an error occurs in server.js:

TypeError: Cannot read properties of undefined (reading 'image')

The variable req.files has become undefined

What is the problem?

CodePudding user response:

    'Content-Type': 'x-www-form-urlencoded',

You're overriding the Content-Type header the browser was sending with the request.

Since the new value is wrong, the server doesn't know how to parse the body.

Don't do that.

  • Related