Express receiving string instead of boolean

Viewed 497

This question has been asked before but the question did not address the sending method and the solution marked does not work for me.

I am trying to get a boolean in a JSON object on the back end but I get a string instead.

I am sending an array of objects from axios with this:

const data = [{
  clientName: 'A client',
  columns: [{ 
    name: 'Keywords', 
    options: [{
      keyword: false,
      include: true
    }] 
  }]
}]

await axios.post('/config', { data })

But when I try to see what type are the options I get strings instead of booleans

On the back end I have this

server.js

import express from 'express'
import cors from 'cors'
import config from './routes/config.js'

const prod = process.env.NODE_ENV === 'production'
const app = express()

// Middleware
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(express.static('uploads'))

app.use('/config', config)


// Start
const port = process.env.PORT || prod ? 5002 : 4003
app.listen(port, () => console.log(`Listening on port ${port}.`))

And the route

config.js


import { Router } from 'express'
import { writeFile } from 'fs/promises'


router.post('/config', async (req, res) => {
  const { data } = req.body.data

  // I want to write the data array with all of its objects however many they are, to file
  await writeFile(config.json, JSON.stringify(data)) 


  console.log(data)
}

export default router
[{
  clientName: 'A client',
  columns: [{ 
    name: 'Keywords', 
    options: [{
      keyword: 'false', // <-- string
      include: 'true'   // <-- string
    }] 
  }]
}]

############## UPDATE

My bad, I thought the react front end was sending booleans, it turns out they were actually strings

<option value={true}>Keyword</option>
<option value={false}>Domain</option>
2 Answers

Assuming the entire object is not a string and only the values are strings you can parse them.

JSON.parse(data[0].columns[0].options[0].keyword);

i think this is the wrong

app.use(express.urlencoded({ extended: true }))

you are using urlencoded

you need to use bodyParser, do this to import body-parser

var bodyParser = require('body-parser');

and use that

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
Related