0

Want response in JSONP format instead of JSON in nodejs using aws lambda and api gateway. my lambda code is:

var axios = require("axios");

exports.handler = async (event) => {
  return new Promise((resolve, reject) => {
    var data = JSON.stringify({
      username: event.username,
      password: event.password,
    });
    var config = {
      method: "post",
      url: "http://demo.example.net/v2/api/login",
      headers: {
        "Content-type": "application/json",
      },
      data: data,
    };
    axios(config)
      .then(function (response) {
        const res = {
          statusCode: 200,
          body: "callbackParam([" + JSON.stringify(response.data) + "])",
        };
        resolve(res.body);
      })
      .catch(function (error) {
        const err = {
          statusCode: 401,
          body: error,
        };
        reject(err.body);
      });
  });
};

getting Response like:

"callbackParam([  {"token":"<token>","expiration": "2022-04-28T08:00:25Z"}])"

can anyone help me what i need to implement extra stuff to convert this response string to jsonp?

my expected response is callbackParam([{}])

0

1 Answer 1

0

I imagine you just need to respond with the appropriate content-type and body for a JavaScript resource.

You're also falling prey to the explicit promise construction anti-pattern so best avoid that too

exports.handler = async ({ username, password }) => {
  const { data } = await axios.post("http://demo.example.net/v2/api/login", {
    username,
    password,
  });

  return {
    statusCode: 200,
    headers: {
      "content-type": "application/javascript",
    },
    body: `callbackParam(${JSON.stringify([data])})`,
  };
};
1
  • Thank you Phil for your answer. I resolved it by applying content-type as you mentioned but I did that at Api gateway integration response mapping template and its worked as expected. Commented May 3, 2022 at 6:53

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.