Unexpected token – in JSON at position 0 (express js server)

Issue

I am trying to send form data to my express js backend.

for my backend server i have this in my server.js file

import express from 'express';
import { routes } from './routes/routes.js'
import connectdb from './model/db.js'
import { getAll } from './model/db.js';

const app = express();
const {projectRoute, fileRoute} = routes

// json parser
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*")
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
  next()
})

const port = process.env.PORT || 5000;

// database connection 
connectdb()


// router for all the project endpoint
app.use("/project", projectRoute);
// router for all the files endpoint
app.use("/files", fileRoute);

app.listen(port, () => {
  console.log(`listening at port ${port}`);
});

and in the controller file for the "fileRoute", i’m simply trying to see what gets sent in the req.body object.
This is the form data i send

form data sent in request

But each time i send the request using VS code Thunderclient, i get this error

request headers and result

Unexpected token – in JSON at position 0 (express js server)

and when i set the content-type header to application/x-www-form-urlencoded i get req.body sent back as this

{   "----------------------------482425439322439335041238\r\nContent-Disposition: form-data; name": "\"project\"\r\n\r\nHTML Project\r\n----------------------------482425439322439335041238\r\nContent-Disposition: form-data; name=\"date\"\r\n\r\n2022-08-10\r\n----------------------------482425439322439335041238--\r\n" }

i don’t understand why this is hapening, can anyone help??

i expected a json body as my result, and when i used a json validator to check this response

{   "----------------------------482425439322439335041238\r\nContent-Disposition: form-data; name": "\"project\"\r\n\r\nHTML Project\r\n----------------------------482425439322439335041238\r\nContent-Disposition: form-data; name=\"date\"\r\n\r\n2022-08-10\r\n----------------------------482425439322439335041238--\r\n" }

it returned VALID (RFC 8259)

Solution

Ok .. so i still haven’t found a solution to this problem on the internet. Although it did start working normally a few days after posting this question, unfortunately the issue came back and has persisted since.

So instead of crying about it, i decided to create a solution of mine, so i wrote my own body parser middleware based on the result i was getting.
Here’s the code 👇

export function localBodyParser(req, res, next) {
    if (typeof req.body !== 'object') {
        return next()
    }
    let keys = []
    let val = []
    let inputsArr 
    let finalInputsArr = []
    for (const key in req.body) {
        keys.push(key)
        val.push(req.body[key])
    }
    if (keys.length > 0) {
        if (keys[0].split('')[0] === '-') {
            inputsArr = val[0].split('=')
            for (let i = 0; i < inputsArr.length; i++) {
                const fieldGroup = []
                fieldGroup.push(inputsArr[i].split('\"')[1])
                fieldGroup.push(inputsArr[i].split('\"')[2].split('\n')[2].split('\r')[0])
                finalInputsArr.push(fieldGroup)
            }
            let body = {}
            for (let i = 0; i < finalInputsArr.length; i++) {
                body[`${finalInputsArr[i][0]}`] = finalInputsArr[i][1]
            }
            req.body = body
            return next()
        }
        return next()
    }
    next()
}

and referenced it in server.js like so

app.use(express.urlencoded({ extended: true, type: 'multipart/form-data' }));
app.use(localBodyParser)

you have to add the express.urlencoded({ extended: true, type: 'multipart/form-data' }) because it needs it to work.

If anyone experiences this issue in the future, and finds a better solution, please feel free to add your solution, else you can use this 😇

Answered By – Jriffs

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published