Home > Net >  req.body is unidentified in express api
req.body is unidentified in express api

Time:07-08

I am implementing stripe payment in my react native app and created express api to get clientSecret Intent. So I want to make payment of the amount which I send from my api to api. But in api, I am getting nothing in the request body.

This is how I am calling my Apis

let data={totalAmount:amount, name:'XYZ_Name'}
fetch('http://10.0.2.2:3500/create-payment-intent', {
  method: 'POST',
  headers: { "Content-Type": "application/json" },
  // "Content-Type" : "application/json",
  body:data,
})

And this is my express api;

const app = express();



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


app.post('/create-payment-intent', async (req,res)=>{
   
    console.log('api Data',req.body.amount);
    const paymentIntent = await stripe.paymentIntents.create({
        amount:5000, //$50
        currency:'gbp',
    });
    
    res.send({
        clientSecret: paymentIntent.client_secret,
        paymentIntent,
        
    })
})

app.listen(3500,()=>{console.log('API Running!')});

CodePudding user response:

Your data must be stringified

let data = { totalAmount:amount, name:'XYZ_Name' }
fetch('http://10.0.2.2:3500/create-payment-intent', {
  method: 'POST',
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(data)
})

CodePudding user response:

I see two issues with the frontend code you shared.

First, you should replace totalAmount: amount by amount: amount, since the backend code is using req.body.amount.

Second, you can't directly send a JavaScript object using fetch, you need to convert it into a string with JSON.stringify(data).

With these two fixes, your frontend code should look like this:

let data= { amount: amount, name: 'XYZ_Name' };

fetch('http://10.0.2.2:3500/create-payment-intent', {
  method: 'POST',
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(data),
})

Note that I wouldn't recommend to pass the amount from the frontend to the backend, since a malicious user could directly change the amount in their browser.

  • Related