AxiosError Request failed with status code 400

Good morning, I’m trying to run a code and it keeps giving the following error:

Could you help me understand where I can improve?

Hi @sarah.pinheiro,

I apologize for the inconvenience you’re facing. It looks like there’s a syntax error in your code. Based on the error message, it seems that you have an unexpected token , at line 2. Please double-check your code and make sure you have the correct syntax. If you need further assistance, please share the relevant code snippet, and I’ll be happy to help you debug the issue.
I’m a bot powered by Pipedream and GPT-4. I’m still learning, so please double check my answers and code! Learn how to build your own.

My code:

// To use any npm package on Pipedream, just import it
import axios from "axios"

export default defineComponent({
  async run({ steps, $ }) {
    const { data } = await axios({
      method: "POST",
      headers: {
      "Content-Type": "application/json",
      "Authorization": "Token dde315be43cf21dceb3be1c3e684fa8251"
      },
      data: {
        "flow": "d53c0fff-543d-4fb4-b04c-f90427ad6de",
        "contacts": ["43332d3b-68f7-4d12-b52e-016b2764688"],
        "params": steps.trigger.event.body
      },
      url: "https://new.push.al/api/v2/flow_starts.json"
    })
  },
})

Hi @sarah.pinheiro,

The HTTP 400 error means that the request you are sending is not in the format the app is expecting. I would first take a look at the params you are sending.

Note: you have exposed your API credentials, you should revoke the token and create a new one ASAP

Don’t worry, this token and information are examples. Thank you, I will check the parameters :slight_smile:

AxiosError: Request failed with status code 400
at settle (C:\Users\User\OneDrive\Desktop\Bus ticket system\node_modules\axios\dist\node\axios.cjs:1967:12)
at IncomingMessage.handleStreamEnd (C:\Users\User\OneDrive\Desktop\Bus ticket system\node_modules\axios\dist\node\axios.cjs:3066:11)
at IncomingMessage.emit (node:events:529:35)
at endReadableNT (node:internal/streams/readable:1368:12)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
at Axios.request (C:\Users\User\OneDrive\Desktop\Bus ticket system\node_modules\axios\dist\node\axios.cjs:3877:41)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async generateToken (C:\Users\User\OneDrive\Desktop\Bus ticket system\Routes\booking.js:27:24) {
code: ‘ERR_BAD_REQUEST’,
config: {
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
},

I’m getting the error above below is my code

const express = require(‘express’)
const router = express.Router()
const axios = require(‘axios’);
const Transaction = require(‘…/models/Transactions.js’)

// Route for the booking page
router.get(‘/booking’, (req, res) => {
console.log(‘reached the booking page’);
res.render(‘booking.ejs’);
})

// Route for the booking page
router.post(‘/booking’, (req, res) => {

const { fare } = req.body;
res.render('booking.ejs', { fare });

});

// Middleware to generate access token
const generateToken = async (req, _, next) => {
const secret = process.env.SAFARICOM_CONSUMER_SECRET;
const consumer = process.env.SAFARICOM_CONSUMER_KEY;
const auth = Buffer.from(${consumer}:${secret}).toString(‘base64’);

try {
  const response = await axios.get("https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials", {
    headers: {
      Authorization: `Basic ${auth}`, 
    }
  });

  req.token = response.data.access_token;
  next();
} catch (err) {
  console.log(err);
  next(err); // Pass the error to Express error-handling middleware
}

};

// Route to send stk push to Safaricom
router.post(‘/stk’, generateToken, async (req, res, next) => {
const phone = req.body.phone.substring(1);
const amount = req.body.amount;

try {
  // Your code for stk push here

  // Assuming stkResponse contains the response from Safaricom
  console.log(stkResponse.data);

  // Checking if the user canceled the transaction
  if (stkResponse.data.ResponseCode === "0") {
    // Store the transaction in the database only if the response code is '0'
    var newTransaction = new Transaction({
      amount: amount,
      phone: phone,
      status: 'Incomplete'
    });

    await newTransaction.save();
  }

  res.status(200).json(stkResponse.data);
} catch (error) {
  console.error(error);
  // Pass the error to Express error-handling middleware
  next(error); 
}

});

router.post(‘/callback’, express.json(), (req, res) => {
console.log(‘Received callback request:’, req.body);
const callbackData = req.body;
console.log(‘Parsed callback data:’, callbackData);
res.status(200).send(‘Callback received’); // Sending a response to acknowledge receipt
});

module.exports = router