Lorteau Erwan
Lorteau Erwan

Reputation: 103

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

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 ?

Upvotes: 0

Views: 291

Answers (2)

shoaib husain
shoaib husain

Reputation: 1

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

Upvotes: 0

DEV
DEV

Reputation: 1726

Are using the middleware properly

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

app.use(express.json());

Upvotes: 1

Related Questions