Home > other >  How do I send JSON data to node.js server using fetch?
How do I send JSON data to node.js server using fetch?

Time:07-04

I have a node.js back-end server. Front-end is running on Angular 10. I want to pass data from front-end to back-end using fetch

Front-end code :

testmariadb($event: MouseEvent) {
    return fetch('/api/customQuery', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({
        sqlQuery: 'SELECT * FROM software'
      })
    })
  }

Back-end code

app.post('/api/customQuery', async (req, res) => {
  let test = req.body['sqlQuery'] 
  console.log(test)
})

I get this error :

  let test = req.body['sqlQuery'] 
                     ^

TypeError: Cannot read properties of undefined (reading 'sqlQuery')
    at /home/erwan/Documents/GitHub/serverAltertManager/index.js:90:22

What I'm doing wrong ?

CodePudding user response:

Are using the middleware properly

const express = require('express');
const app = express();

app.use(express.json());

CodePudding user response:

testmariadb() { fetch('APIURL', { method: 'POST', headers: {'Content-Type': 'application/json; charset=UTF-8'}, body: JSON.stringify({ key: 'Value' }) }).then((result)=>{ return result }) }

  • Related