Home > Back-end >  there is no request body consumed when it called by ajax
there is no request body consumed when it called by ajax

Time:03-06

I got a problem with ajax when I call rest API post method, I use the nodeJS to build the API side the script looks like

const route = express.Router();

route.post('/tambahproduk',async(req,res)=>{
console.log("API 3");
try {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested- 
    With, Content-Type, Accept");
  
    let response = await ProdukController.tambahproduk(req,res)
    return res.send(response) 
} catch (error) {
    console.log(error,`eror`);
    return res.send(response("500",error))
}
})

the function that called from route bellow

async function tambahproduk(req,res){
const {
   param1,param2
} = req.body;
let obj = {}

    console.log(req.body,param1);
try {
    const request = await DB.CONDB.promise();
    let insert = `insert query`
    
    console.log(insert);
    // let data = await request.query(insert)
    if(data){
        obj = respone("200",`Success)
    }else{
        obj = respone("500",`Failed)
    }
    return obj
}catch(err){
    console.log(err);
    obj = respone("500",err)
    return obj
}
}

so I try to call it with ajax in the client side

$.ajax({
        type:'POST',
        url:`${uri}/blabla/blablabla`,
        data:{
          param1: "asd",
          param2: "123"
        },
        success: function(data){
            console.log(data);
        }
  })
}

enter code here

but the response filed param1 is undefined, and even I tried to logging the req.body is there is no data consumed. please help me to fix it ? thanks

CodePudding user response:

You did not really show how the rest of your code looks like. I'm providing the minimal working example for your case.

// Server
const express = require('express');

const app = express();

app.use(express.urlencoded({ extended: false }));

// If you want to get payload as a JSON object instead of FormData 
// uncomment the line below
// app.use(express.json());

app.post('/products', function(req, res) {
  // Get request body parameters
  const {param1, param2} = req.body;

  res.json({
    param1,
    param2
  });
});
// Client
$.ajax({
  type:'POST',
  url:`/products`,
  data:{
    param1: "123",
    param2: "123"
  },
  success: function(data){
    console.log(data);
  }
})

After running it you get response

{param1: '123', param2: '123'}

Here is a curl command.

curl \ 
 -X POST \ 
 -d "param1=123&param2=123" \
 -H "Content-Type: application/x-www-form-urlencoded" \
 http://127.0.0.1:3000/products

Assuming application runs on http://127.0.0.1:3000.

As you notice this request requires the header Content-Type: application/x-www-form-urlencoded however in your jQuery ajax req it's automatically added.

  • Related