Put request in strapi - javascript

I have a table of users, a user has favorite items, one user can have many items. In the admin panel, I can freely add/remove items, but how can I do this in the form of a request?
I am interested in the mechanism itself, the process of adding and removing elements. I have the necessary ID to delete and add. How to write correctly?
I need a PUT request
async updateFavorites(id, status) {
let {
data,
error
} = await useFetch(
`${useRuntimeConfig().env.STRAPI_URL}/api/users/${this.user.id}`, {
method: "PUT",
headers: {
Authorization: `Bearer ${this.jwt}`,
"Content-Type": "application/json",
},
body: {
}
}
);
}

To add a new element to the array, I just added a new id to the array, strapi picked up the id itself and found a match. If there is a relationship with another element in the table, it is enough to add an id.
this.user.Favorites.push(id);
let { data, error } = await useFetch(
`${useRuntimeConfig().public.strapi.url}/api/users/${this.user.id}`,
{
method: "PUT",
headers: {
Authorization: `Bearer ${cookie.value}`,
"Content-Type": "application/json",
},
body: {
Favorites: this.user.Favorites,
},
}
);

Related

send request using Fetch method

I need to send request using 'fetch' method. I need to send below data to my header
I need to send below data in request body
i am trying to do it using below code. but actually I have not proper idea to do it. can u help me.
fetch("http://disaida.com/api/endpoint/", {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
PREPAY: ppy,
InputParameters: int
})
})
.then( (response) => {
});
Your data format is incorrect.
TRY
Also, based on your description, you might have to add the cookie property to your header
let data = {
PREPAY: {
InputParameters: {
P_USER_NAME : "SANJEEWA.LAKNATH1#HUAWEI.COM"
}
}
}
fetch("http://disaida.com/api/endpoint/", {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then( (response) => {
console.log("RR"+response.json())
}).catch(err => console.log("error",err));

Axios POST request not working with MailChimp API?

I am trying to post an email to my list on MailChimp. I am using axios and react to try and achieve this task.
Currently, when the request is made I am not receiving any response back but rather getting a (failed) net::ERR_FAILED.
const handleSendEmail = () => {
axios.post('https://usX.api.mailchimp.com/3.0/lists/XXXXXXXXXX/members/', {
headers: {
'Authorization': `Basic properlivingproperty:${api_key}`,
'Accept': 'application/json',
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*"
},
body: JSON.stringify({
email_address: email,
status: "subscribed"
},{
auth: {
'username': `SOMEUSERNAME`,
'password': `${api_key}`
}})
}).then(response => {
console.log(response.data)
}).catch(error => {
console.log(error.data);
});
}
It is not posting and saving the email on my MailChimp account
In axios post:
The 1st argument is the url.
The 2nd argument of axios.post is the data that you need to post.
The 3rd argument takes options (headers etc).
In your code, the 2nd argument is taking the options.
So, change your code to:
const data = {
email_address: email,
status: "subscribed"
};
const options = {
headers: {
'Authorization': `Basic properlivingproperty:${api_key}`,
'Accept': 'application/json',
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*"
}
};
axios.post('/apiEndpoint', data, options)
.then((response) => {
...
})
.catch((error) => {
...
})
You can also provide 1 arg to axios post, in that case it has to be an object containg all info (url, data, options etc.)
See here for details

Javascript Fetch Body JSON List

I am trying to make a post request and getting this exception:
"unsupported BodyInit type"
I think the issue is with the body of the request. phoneNumbers takes on the form phoneNumbers = ["1234567890", "1234567891"] (i.e. a list of strings). I tried to do JSON.stringify(phoneNumbers) as the body, but that seems to return "[]", even if the list is not empty.
export async function findUsersByPhoneNumbersNotFollowing(userId, phoneNumbers) {
const reqConfig = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: phoneNumbers,
};
const response = await authfetch(`${API_URL}/following/recommendations/${userId}`, reqConfig);
if (response.error) {
throw new Error(response.error);
}
return response;
}
Where am I going wrong? The API endpoint is expecting List<String> (using spring framework, and the controller method takes this param in annotated #RequestBody)
Try sending a JSON Object instead a plain array:
const reqConfig = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({
paramName: phoneNumbers
}),
};
Replace paramName for the name you are expecting on your API endpoint.

Converting fetch PUT request into axios request

I have been using fetch on the frontend to make a PUT request. My code looked like the following:
fetch(url, {
headers: {
'content-type': 'png',
},
method: 'PUT',
body: file,
})
I am trying to write the same using axios but doesn't seem to be working
await axios.put(url, {
data: {
body: file
},
headers: {
'content-type': 'png',
},
})
Take a look at the axios.put signature:
axios.put(url[, data[, config]])
The second argument is treated as data, so your headers end up as part of the request body.
Further, data: { body: file }, is redundant. axios.put()'s data argument is already treated as body.
So you can either do:
await axios.put(url, file,
{
headers: {
'content-type': 'png'
}
}
)
or:
await axios.put(url, {},
{
data: file,
headers: {
'content-type': 'png'
}
}
)
Or, for even more resemblance with fetch API,
await axios(url,
{
method: 'PUT',
data: file,
headers: {
'content-type': 'png'
}
}
)

How can I add raw data body to an axios request?

I am trying to communicate with an API from my React application using Axios. I managed to get the GET request working, but now I need a POST one.
I need the body to be raw text, as I will write an MDX query in it. Here is the part where I make the request:
axios.post(baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
{
headers: { 'Authorization': 'Basic xxxxxxxxxxxxxxxxxxx',
'Content-Type' : 'text/plain' }
}).then((response) => {
this.setState({data:response.data});
console.log(this.state.data);
});
Here I added the content type part. But how can I add the body part?
Thank you.
Edit:
Here is a screenshot of the working Postman request
How about using direct axios API?
axios({
method: 'post',
url: baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
headers: {},
data: {
foo: 'bar', // This is the body part
}
});
Source: axios api
You can use postman to generate code. Look at this image. Follow step1 and step 2.
If your endpoint just accepts data that have been sent with Body (in postman), You should send FormData.
var formdata = new FormData();
//add three variable to form
formdata.append("imdbid", "1234");
formdata.append("token", "d48a3c54948b4c4edd9207151ff1c7a3");
formdata.append("rate", "4");
let res = await axios.post("/api/save_rate", formdata);
You can use the below for passing the raw text.
axios.post(
baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
body,
{
headers: {
'Authorization': 'Basic xxxxxxxxxxxxxxxxxxx',
'Content-Type' : 'text/plain'
}
}
).then(response => {
this.setState({data:response.data});
console.log(this.state.data);
});
Just have your raw text within body or pass it directly within quotes as 'raw text to be sent' in place of body.
The signature of the axios post is axios.post(url[, data[, config]]), so the data is where you pass your request body.
The key is to use "Content-Type": "text/plain" as mentioned by #MadhuBhat.
axios.post(path, code, { headers: { "Content-Type": "text/plain" } }).then(response => {
console.log(response);
});
A thing to note if you use .NET is that a raw string to a controller will return 415 Unsupported Media Type. To get around this you need to encapsulate the raw string in hyphens like this and send it as "Content-Type": "application/json":
axios.post(path, "\"" + code + "\"", { headers: { "Content-Type": "application/json" } }).then(response => {
console.log(response);
});
C# Controller:
[HttpPost]
public async Task<ActionResult<string>> Post([FromBody] string code)
{
return Ok(code);
}
https://weblog.west-wind.com/posts/2017/sep/14/accepting-raw-request-body-content-in-aspnet-core-api-controllers
You can also make a POST with query params if that helps:
.post(`/mails/users/sendVerificationMail`, null, { params: {
mail,
firstname
}})
.then(response => response.status)
.catch(err => console.warn(err));
This will POST an empty body with the two query params:
POST
http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName
Source: https://stackoverflow.com/a/53501339/3850405
Here is my solution:
axios({
method: "POST",
url: "https://URL.com/api/services/fetchQuizList",
headers: {
"x-access-key": data,
"x-access-token": token,
},
data: {
quiz_name: quizname,
},
})
.then(res => {
console.log("res", res.data.message);
})
.catch(err => {
console.log("error in request", err);
});
This should help
You can pass the params like so
await axios.post(URL, {
key:value //Second param will be your body
},
{
headers: {
Authorization: ``,
'Content-Type': 'application/json'
}
this makes it easier to test/mock in Jest as well
I got same problem. So I looked into the axios document.
I found it. you can do it like this. this is easiest way. and super simple.
https://www.npmjs.com/package/axios#using-applicationx-www-form-urlencoded-format
var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
You can use .then,.catch.
For sending form data in the body, you can just format the data in url params like this 'grant_type=client_credentials&client_id=12345&client_secret=678910' and attached it to data in the config for axios.
axios.request({
method: 'post',
url: 'http://www.example.com/',
data: 'grant_type=client_credentials&client_id=12345&client_secret=678910',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
})
The only solution I found that would work is the transformRequest property which allows you to override the extra data prep axios does before sending off the request.
axios.request({
method: 'post',
url: 'http://foo.bar/',
data: {},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
transformRequest: [(data, header) => {
data = 'grant_type=client_credentials'
return data
}]
})
This worked fine for me when trying to send authentication credential in body in raw json format.
let credentials = {
username: "your-username",
password: "your-password",
};
axios
.get(url, { data: credentials })
.then((res) => {
console.log(res.data);
})
Used in React js
let url = `${process.env.REACT_APP_API}/validuser`;
let body = JSON.stringify({
loginid: "admin",
password: "admin",
});
var authOptions = {
method: "post",
url: url,
data: body,
headers: {
"Content-Type": "application/json",
},
json: true,
};
axios(authOptions)
.then((resp) => {
console.log("response :- ",resp);
})
.catch((error) => {
alert(error);
});
axios({
method: 'post', //put
url: url,
headers: {'Authorization': 'Bearer'+token},
data: {
firstName: 'Keshav', // This is the body part
lastName: 'Gera'
}
});
There many methods to send raw data with a post request. I personally like this one.
const url = "your url"
const data = {key: value}
const headers = {
"Content-Type": "application/json"
}
axios.post(url, data, headers)
let url='<your domain.extension>';
let data= JSON.stringify('mydata');
axios
.get(url, { data })
.then((res) => {
console.log(res.data);
})
For me this solution works, i.e. JSON.stringify(your data) , just convert your raw data using JSON.stringify method.
I hope this works.

Categories

Resources