Node receive post json from axios post - node.js

I have 2 different url, the first one receive a form action from an html page with the data and make a post request to the second url. This receive the json and with express make a get request with this json.
How can I read a json that I receive from another url with post request made with axios?
Thanks

Usually, Axios response returns an object containing data;
const {data: json} = await axios.post(/*details*/);
console.log(json);

Related

How to Send request body in Redirect twilio

How to pass request body in Twilio redirect? since there is a limit for the header length and need to send huge data one function to another function.
const VoiceResponse = require('twilio').twiml.VoiceResponse;
const response = new VoiceResponse();
response.redirect({
method: 'POST'
}, 'http://pigeons.com/twiml.xml');
console.log(response.toString());
Twilio developer evangelist here.
When using TwiML <Redirect> you cannot affect what is sent in the request body to the next URL. If you want to pass information to the next URL you can add query string parameters to the URL. You can also set cookies on the TwiML response which will be sent back to your server with the next request.
If you have data that is too big for you to send in either of those formats, then you might want to store it on your server side in a database and then send the ID of the record over query string parameters or cookies, so that you can use the ID to retrieve the data in the next request.

Post a simple react form - node, axios, nodemailer, backend, postman

I've set up a react form running on http://localhost:3000/about and I've the backend running on port 5000 (localhost:5000). On react's package.json I set up "proxy":"localhost:5000:.
When I use postman and I send the post to localhost:5000/api/contact, the email is sent correctly (I send the data as JSON - name, email and message). Status 200
When I use the react form, the data is well prepared as json but I can't figure out the baseURL to send correctly the method post. status 404. I tried:
localhost:3000/about/api/contact;
localhost:3000/api/contact;
localhost:3000/api.... None works...
FYI
the server is set up with the following middleware and is working ok:
app.use('/api',contactRoute)
the controller is imported and coded as following:
router.post('/contact', (req, res)=>{
const data = req.body;
The React part is not posting correctly with axios and is coded as following:
onSubmit: async (values) => {
//values.preventDefault();
try {
const data = (JSON.stringify(values, null, 2))
setLoader(true);
console.log(data)
await axios.post('/contact', data);
The method post in react is never completed, when I check the console.log of data, is correctly structured as JSON...status 404
use the post parameter in your axois request {port: 5000} then It will use your actual backend port.
By default, axios uses the base path from the URL. So, here when an API request is made.
await axios.post('/contact', data);
It is actually making the post request on localhost:3000 rather than your backend server at localhost:5000. Also, "api" should also be prepended.
One simple way is to use absolute URL which should work.
await axios.post('http://localhost:5000/api/contact', data);

NodeJs with Express not parsing form data from node-fetch

I'm creating two APIs with NodeJS, Express, and TypeScript. One API will take a request with a content type of multipart/form-data, and will use the body in the request to make another request to a second API.
I'm using Postman, so the chain of request looks something like this
Postman -> First API -> Second API
I use node-fetch to make a request from the first API to the second one. The body of the request is a FormData, which contains some files and key-value pairs.
const form = new FormData();
// File for profile picture
const profilePictureBuffer = await (await fetch(user.profilePicture)).buffer();
form.append('profilePicture', profilePictureBuffer);
// File for ID Card
const idCardBuffer = await (await fetch(user.idCardUrl)).buffer();
form.append('idCard', idCardBuffer);
// This part iterats over the obsect of 'user',
// which contains other key-value pairs
Object.entries(user).forEach((data) => {
form.append(data[0], data[1]);
});
// Make POST request to second API
const pinterUser = await fetch(secondAPIURL, {
method: 'post',
body: form,
headers: form.getHeaders()
});
I ran both of the APIs on localhost so that I can monitor the logs for any bugs. As I make a request from Postman to the first API, then the first API make another request to the second API, I got the following error log in the terminal for the second API
TypeError: Cannot read property '0' of undefined
After some investigation, I found out that, in the second API, the req.body and req.files are empty objects. This means that Express did not parse the incoming request. Note that I've also already a multer middleware to handle the files in the request.
Furthermore, I have added the following lines of code in my server.ts file for the second API
/** Parse the body of the request */
router.use(express.urlencoded({ extended: true }));
router.use(express.json());
However, when I tried making the request from Postman, it returns a successful response.
I'm not really sure what's going on here. I've tried looking for some answer regarding this similar issue, but most of them suggest adding urlencoded and json, or using some other library to handle parsing form data.
In my case, the first suggestion doesn't solve my problem since I already added them from the start, and the latter is what I'm trying to avoid.
I wonder if anybody could point out what I was missing here? Thanks in advance

How to get post body with Koa-router-forward-request?

I have the koa-router-forward-request set up. I make an axios call to it and that call is forwarded onto an API. I can do get requests and retrieve the information. I can't get post requests working. I want to forward the post request body from the original axios call onto the API how do I do that?
I have const composeRequest = body;
and in the request I have composeBody: composeRequest as an attribute but that does not seem to be working.
This is super late but I think what you are looking for is maybe to 1. ensure you are using bodyParser() i.e. router.use(bodyParser()) and 2. when hitting the Koa route pull any params you pass via Axios by ctx.request.body, all params should be stored in there to pull out.

Get Data from POST request on client side

I made a form post request from my react front end. In my express route I handle it, and I send the data to the browser, as such:
app.post("/api/fetchuser", async (req, res) => {
// Doing some stuff here
res.send(req.body.user);
});
My question is: How can I get the data from this POST request route back to my client side? Previously, I did axios.get(...) to retrieve data on a app.get(...) route in a similar fashion, however, this is a POST route. How can I solve this issue?
Just do axios.post request. See Performing a POST request section of axios documentation.
Edit: Yes you can also retrieve data by POST request. You don't have to post any data to the server while performing the request.
axios.post('/api/fetchuser/',{})
.then(res => console.log(res.data));

Resources