Home > OS >  Redirect the user to the URL of REST API after sending the post request using Needle
Redirect the user to the URL of REST API after sending the post request using Needle

Time:02-01

I am working with a REST API that as a result of a POST request to an address like https://example.com/api returns an HTML webpage (instead of JSON or other data formats).

Normally on the front-end side dealing with such scenario is not difficult to manage using a code like this:

<form action="https://example.com/api" method="POST">
  <input type="text" name="param1" value="test1">
  <input type="text" name="param2" value="test2">
  <input type="submit">
</form>

In that case only pressing the submit button results in loading the URL https://example.com/api with the right parameters. However, I am unable to replicate this on server-side code using Node js and Needle library.

I used a code snippet like this:

let params = {
  param1: "test1",
  param2: "test2"
};

let options = {
  headers: {
    "Content-Type": "application/x-www-form-urlencoded"
  }
};

needle.post("https://example.com/api", params, options, function (err, response) {
  console.log(response.body);
  //what should i do here?
});

but at this point, I don't know how to redirect the client to the address. The response.body property contains the webpage HTML but sending it directly using:

res.send(response.body);

leads to distorted webpage appearance due to missing css files and relative URLs. Also redirecting directly to the webpage in the callback seems not to work:

res.redirect("https://example.com/api");

CodePudding user response:

I think I figured that out myself, we can just use URL queries just like the GET requests:

res.redirect("https://example.com/api?param1=test1&param2=test2");
  • Related