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
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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¶m2=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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0