Modiy axios request 'data' field into 'body' - node.js

I'm trying to create a POST request using axios to a Notification API. So this Notification API have been developed before thus I cannot change anything related to it.
It accepts the request more or less like below.
I need to have the request body in the field called body as shown below. However, axios sends the request body in the field called data rather than body
Expected request
{
"head": {
...
},
"body":{
"publicUserId":"abcd",
"merchantId":"123888",
}
},
}
My request composed automatically by axios:
Axios request
{
"head": {
...
},
"data":{
"publicUserId":"abcd",
"merchantId":"123888",
}
},
}
I did try searching for how to alter the request body field name to body instead of data but I'm pretty sure I haven't found the solution. Maybe if anyone here has some workarounds, I'd be glad to try.
Should any details need to be provided, please tell me. Thank you.

Related

How do i handle an api response with a header, response code, and body, using retrofit2?

I have an API that returns a response with a header, status code, and body field. How do I correctly handle this using retrofit, and Kotlin Coroutines? I'm used to a simple implementation such as below, but this does not work since the API is not just the JSON body.
Typical implementation:
interface MyApi {
#GET("myapi")
suspend fun getData() : DataClass
}
With the following response, the above implementation does not work:
{
statusCode=200.0,
headers={
x-custom-header=my custom header value
},
body={
"name":"John",
"message":"Hello"
}
}
Do I need to create a wrapper class for this new type of response? Then, to access the data just call WrapperClass.body? Or is there a more elegant solution to this?

I am facing issue while reading request body in Azure function node js

In my azure function post call i am passing body like this
{
"license":{
"licensepolicy": "NA",
"metadata":{
"tenantname":"tenantname",
},
"licensetype":"type"
},
"customer":{
"name":"TEst User",
"emailaddress":"email",
"company":"test"
}
}
In my code I am accessing this request body like below
context.log(req.body.license);
Its giving undefined log, I don't know why but its working in normal node js code but in azure function its not working.
Please assist me if I am wrong somewhere
thanks in advance
Make sure to check your post method whether it contains the Header 'Content-Type': 'application/json'
headers: {
'Content-Type': 'application/json'
}
If you are not sending the Json response you have to convert that into Json object in your code to retrieve that information.
# convert request into Json object and access those informations.
const parsedData = JSON.parse(req)
context.log(parsedData.body.license);

Importing excel file in a form then with onSubmit fetch POST it to an API endpoint

I have an to make an app that will connect with an API. Through this app i will have to send info to the given API. The required parameters are actually in the first row of the excel file (the headers).
Are you using axios? If yes then you can do something like this.
https://github.com/axios/axios#axios-api
axios.post(url,
{
// for GET requests
params: {
foo: bar
},
// for POST .etc requests
data: {
foo: bar
},
}
);

Why #Body() in Post request is not working properly? [Nest.js]

I'm starting to learn Nest.js, so I am following an Academind Tutorial (link).
My code is not working as expected when I try to get the body variable with the #Body() decorator in the POST request. Following this part of the code in products.controller.ts
#Post()
async addProduct(#Body() body: Product) {
console.log(body);
const generatedId = this.productService.insertProduct(body.title, body.description, 5.99);
return generatedId;
}
In the terminal the output is just an empty object: {}
I have searched for other examples to look at how to do it properly. I found a tutorial in DigitalOcean where they also use #Body in the POST request; they leave a the end of the tutorial a repo with the example. This example is neither working for me.
I just did a small change in addBook() function on book.service.ts file for returning the new book instead of all books
addBook(book): Promise<any> {
return new Promise(resolve => {
this.books.push(book);
// resolve(this.books);
resolve(book);
});
}
I do the following POST request from Postman but an empty object is being the response.
All other HTTP requests are working just nice, except for the POST one.
Any ideas what could be wrong with the code? Thanks in advance. 😃
You're sending form-data which NestJS does not correctly parse by default. You can use application/x-www-url-form-encoded or application/json along with the raw option in Postman. The JSON body would look like so:
{
"id": "7",
"title": "Whatever Title",
"desscription": "whats doc",
"author": "Me"
}
And then your server will recognize the body properly. The other option would be to add in a body parser that properly parses form-data. There are several options out there like multer, form-parser, formidable, and others.
i also faced the same issue, first i tried to send the data as raw format but it didn't worked properly, then i used x-www-urlencoded tab on postman and it solved the issue for me.
Edit: i had a typo in raw format, now it's working fine!
Remove the type (Product) for body works for me.
Not related to the example but related to the title.
If you use ValidationPipe with whitelist=true on your app.
app.useGlobalPipes(new ValidationPipe({ whitelist: true }));
whitelist — removes any property of query that is not part of DTO.
And do not use decorators from the 'class-validator' on your DTO object
import { IsNotEmpty, MaxLength } from 'class-validator';
export class Cat {
#MaxLength(200)
#IsNotEmpty()
name: string;
age: number; // would be removed by ValidationPipe when whitelist=true
}
The properties would be removed. And you will get the empty object.

Validate Request Body variables through Swagger and Express

I am currently using Swagger (2.0) on Node.js. My YAML file validates correctly and the requests are going through. My particular call has a request body using the following format -
{
"postalCode": "invalidpostalcode",
"phone": "invalidnumber",
"website": "invalidwebsite"
}
I would like to validate each body variable before continuing to the next piece of code. To accomplish validating the data I would like to use validator.js.
Now my basic validation code looks something like that -
if(!validator.isURL(req.body.website)){
var tmp = {
"message": req.__('error.url', {
field: req.body.website
})
}
res.status(400).json(tmp);
return;
}
if(!validator.isPostalCode(req.body.postalCode,'any')){
var tmp = {
"message": req.__('error.postalCode', {
field: req.body.postalCode
})
}
res.status(400).json(tmp);
return;
}
Is there there any better way to validate data sent in through the API that would require less code? For example by using a function to control the majority of the logic?
while this is one example of the endpoint I will have some in the future that will require upwards of 20 body parameters.
I have tried create a function that will return the response code. However, that returns an error Cannot set headers after they are sent to the client.

Resources