mistakes in Headers in fetch request - reactjs

I have a fetch request that works in browsers exept IE 11. It gets them from cache. To solve this problem I want to add headers in request.
async getResource(details) {
const mainUrl = "http://www.boredapi.com/api/activity";
const myHeaders = new Headers();
myHeaders.set("Pragma", "no-cache");
myHeaders.set("Cache-Control", "no-cache");
const res = await fetch(`${mainUrl}${details}`, {
mode: "no-cors",
headers: myHeaders,
});
}
I add details according details that user choose(sum of money, number of paricipants) It may look like '?participants=2&minprice=0.1'
And send request
const details = await this.getResource(`?participants=2&minprice=0.1`);
And got a mistake
Unhandled Rejection (Error): Could not fetch ?participants=2&minprice=0.1, received 0

I could solve problem with IE by adding cache: "no-cache", and deleting headers.

Related

How to fix the error when trying to access the API?

I want to generate token to do the CRUD operations in SharePoint Online list. I am able to generate the token in Postman. But I want that it automatically gets generated in my React app to do the CRUD operations. I copied the code snippet from the Postman and pasted in my React app, but it is throwing error. Here is the error :
UsingFetch.js:181 POST https://accounts.accesscontrol.windows.net/834fb7b4-624d-4de8-a977-2d46ad979bd9/tokens/OAuth/2 400 (Bad Request)
{"error":"invalid_request","error_description":"AADSTS900144: The request body must contain the following parameter: 'grant_type'.\r\nTrace ID: d2dcb2da-1aae-4af2-a3e3-aabc35ce4301\r\nCorrelation ID: c90dff14-b64d-4f47-a01c-dfe498ec2f40\r\nTimestamp: 2022-02-23 09:07:45Z","error_codes":[900144],"timestamp":"2022-02-23 09:07:45Z","trace_id":"d2dcb2da-1aae-4af2-a3e3-aabc35ce4301","correlation_id":"c90dff14-b64d-4f47-a01c-dfe498ec2f40","error_uri":"https://accounts.accesscontrol.windows.net/error?code=900144"}
Here is the screenshot of the
Here is the code snippet that I copied from Postman :
const generateToken = async () => {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
myHeaders.append(
"Cookie",
"esctx=AQABAAAAAAD--DLA3VO7QrddgJg7WevrQx7IG43UK7gipYHXtqZImLB1jfBLK4PTkZlgLq3BvpTizt3xt8EZQrpUJGa0hTnSdpRf-AenJvnGNABiv2cWYWSyJj9QNm-vWalRGHuDZ6Km_DaX_5CQHUa4H8U-osEGCM48buOyj0G819e1NoxuvoOD6fZvMI5nnDWZyjNa1mogAA; fpc=An1vbDtRI8BAiCLlUBBGpFXf9_srAQAAACDgp9kOAAAA; stsservicecookie=estsfd; x-ms-gateway-slice=estsfd"
);
var formdata = new FormData();
formdata.append("grant_type", "client_credentials");
formdata.append(
"client_id",
"myclientid"
);
formdata.append(
"client_secret",
"mysecretcode"
);
formdata.append(
"resource",
"00000003-0000-0ff1-ce00-000000000000/cooponline.sharepoint.com#834fb7b4-624d-4de8-a977-2d46ad979bd9"
);
var requestOptions = {
method: "POST",
headers: myHeaders,
body: formdata,
redirect: "follow",
};
await fetch(
"https://accounts.accesscontrol.windows.net/834fb7b4-624d-4de8-a977-2d46ad979bd9/tokens/OAuth/2",
requestOptions
)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
};
Can anyone please provide me with a solution?
Thank you.
This error says what's wrong: The request body must contain the following parameter: 'grant_type'.
To fix this, just add it as a parameter (formData in this case). According to the SharePoint docs, this value must be set to client_credentials.
formdata.append(
"grant_type",
"client_credentials"
);
EDIT:
Apparently, the request body has an unusual format. You're trying to send it as application/json, but MS expects application/x-www-form-urlencoded like this:
POST /{tenant}/oauth2/v2.0/token HTTP/1.1 //Line breaks for clarity
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
client_id=535fb089-9ff3-47b6-9bfb-4f1264799865
&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default
&client_secret=sampleCredentia1s
&grant_type=client_credentials
So, instead of passing formData object as the request body, you should wrap it into a string like this:
const body = Object.keys(formData)
.map(key => `${key}=${formData[key]}`)
.join('&');
and pass that as the body.

NEXTJS Sending formdata to api endpoint - no response

Hellooooo.
I am trying to upload images to AWS S3 and I've stumbled upon something that irritates me quite a lot. I simply can't seem to understand why it would act like this.
Aight so.. I am using formdata to send data to my api endpoint. The API gets called without any issues, no errors, nothing.. Like srly, nothing. Before getting to image upload I was just using a basic body post request with fetch but now I am using formdata in order to upload images.
Here's my "fetch/axios/sendthingy"
const formData = new FormData();
formData.append('file', validFiles[0]);
formData.append('postTitle', postTitle);
formData.append('postProduct', postProduct);
formData.append('postDescription', postDescription);
formData.append('postPrice', postPrice);
formData.append('postCoins', cryptocoins);
formData.append('postCategory', Cate);
formData.append('postSubCategory', subCat);
formData.append('postCryptoDiscount', cryptoDiscount);
for (const entry of formData.entries())
{
// debugging
console.log(entry)
}
var myHeaders = new Headers();
myHeaders.append("Accept", "application/json"); // or form data?
const requestOptions = {
method: 'POST',
body: formData,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, // or use myHeaders
// body: JSON.stringify({ postTitle: postTitle, postProduct: postProduct, postDescription: postDescription, postPrice: postPrice, postCoins: cryptocoins, postImage: validFiles[0], postCategory: Cate, postSubCategory: subCat, postCryptoDiscount: cryptoDiscount})
};
// const res = await fetch(`http://localhost:3000/api/posts/create`, requestOptions)
// const data = await res.json();
axios.post('http://localhost:3000/api/posts/create', formData).then(console.log).catch(console.error)
My comments are from before using formdata. That worked.
As you can see, I have installed Axios. I wanted to see if axios would fix the return stuff. No luck. Any ideas on how to solve this or how to send images to api with or without formdata?
Right, let's move on. Next issue is that I can see it calling my API endpoint but my api endpoint does nothing. It returns nothing. Does nothing. But when I call the api from postman it works just as it should. How come? It creates the post and returns the correct data. Any ideas?
My API:
export default async function handler(req, res) {
console.log('body', req.body);
/*
Redacted
*/
res.status(200).json({response: 'test', code: 200, message:"Successfully created the post."})
})
Why is my API not doing anything locally... It will only work with formdata if I call the endpoint from postman.
This is what I mean.. The dark one is Firefox, white is Postman:
Firstly , you should use multipart/form-data for uploading files. And to see the response you have to console.log the response like this:
axios.post(
'http://localhost:3000/api/posts/create',
formData,
{headers:{'Content-Type':'multipart/form-data'}}
).then(res => console.log(res))
.catch(err => console.error(err))

How to perform a post request with axios on React and pass your data as FormData?

There's this API:http://zssn-backend-example.herokuapp.com/api/, detailed here: http://zssn-backend-example.herokuapp.com/swagger-api/index.html#!/people/Api_People_index . I am trying to do a POST request on this endpoint "/people/{person_id}/properties/trade_item.json"(Make a trade transaction between survivors). On the Website for testing I filled the fields with the following data and got 204 response:
person_id:34e183a6-965e-4a61-8db5-5df9103f4d4b
consumer[name]: Person4
consumer[pick]: AK47:1;Campbell Soup:1
consumer[payment]: First Aid Pouch:2
I investigated a Little and got
this information
didn't understand the "PROPERTY[KEY]:VALUE" representation
When I try to the Request with this code, with the same values(by the way, the database of this API is cleared each 24 hours, so those value might not work, even if you do it in the right way):
this is My code:
async function handleTrade(e){
e.preventDefault();
const config = {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
};
await api.post(
"/people/" + match.params.id + "/properties/trade_item.json",
{
person_id:match.params.id,
name: survivorRef.current,
pick: survivorItemsToPick,
payment: userItemsToPay,
},
config
);
And this is what I get:
Request:
request-description
Response:
response-description
How Can i make this request in the right way in order to get the same result as the first Image ?
You can use FormData to send the request, I made an example:
const data = new FormData();
data.append("customer[name]", "Person4");
data.append("customer[pick]", "AK47:1");
await api.post("/people/" + match.params.id + "/properties/trade_item.json", data, config)

Spring API request giving "Content type 'application/octet-stream' not supported" error, however request is successful when using Postman

I am trying to send an API request through my React frontend to Spring backend. When I send the request I get this error:
Could not resolve parameter [0] in private org.springframework.http.ResponseEntity com.example.bottlecap.controllers.BottlecapController.entryForm(com.example.bottlecap.domian.Bottlecap,org.springframework.web.multipart.MultipartFile): Content type 'application/octet-stream' not supported
However, when I set up the request using Postman it goes through fine. I presume there may be an issue with how I am setting up my FormData on the React end. However, I have had little luck figuring it out.
My API is supposed to recieve an object that holds data about my submission as well as an image that goes with the submission. In my Postman request, I am creating a form data that holds a JSON file that holds all the object data and a random image just for testing. As I said, the requets goes through fine with this. However, in the frontend code, I am parsing through the object data as Json and adding it to a FormData as well as adding the image to the FormData.
Here is my Spring Controller:
#RequestMapping(path ="/bottlecap/entry", method = RequestMethod.POST, consumes = {MediaType.MULTIPART_FORM_DATA_VALUE, MediaType.APPLICATION_OCTET_STREAM_VALUE})
private ResponseEntity entryForm(#RequestPart("cap") Bottlecap cap, #RequestPart("file") MultipartFile image){
System.out.println(cap);
cap.toString();
System.out.println("Test");
return ResponseEntity.ok().build();
}
Here is my react Frontend form submission handler:
handleSubmit = event =>{
console.log(this.state.page);
console.log(this.state.page);
event.preventDefault();
const cap ={
"name":this.state.name,
"brand":this.state.brand,
"yearMade":parseInt(this.state.yearMade),
"country": this.state.country,
"description":this.state.description,
"yearFound":parseInt(this.state.yearFound),
"isAlcoholic":"true"
};
const stringCap = JSON.stringify({cap});
console.log(cap);
var formData = new FormData();
formData.append('cap', JSON.parse(stringCap));
formData.append('file',this.state.imageFile)
axios.post('http://localhost:8080/bottlecap/entry', formData, {headers:{'Content-Type':'multipart/form-data'}})
.then(res=>{
console.log(res);
console.log(res.data);
//window.location = "/success"
this.setState({pageDone:true})
this.setState({pageLoading:true})
})
}
Here is a screenshot of my Postman request if it may help.
Also here is the contents of the json file I am sending through on Postman, if it may help as well.
{"name":"post-test",
"brand":"post-test",
"yearMade":1000,
"country":"post-test",
"description":"post-test",
"yearFound":1000,
"isAlcoholic":"true"}
The last change I did was adding a header to the axios API request, but still no luck.
In postman, for parameter named cap, you're sending a .json file. But in your reactjs code, you're doing
formData.append('cap', JSON.parse(stringCap));
JSON.parse will create a javascript object which is not what your backend is expecting. You need to send it as a JSON file.
Not tested, but this might give you the idea.
const json = JSON.stringify(cap);
const blob = new Blob([json], {
type: 'application/json'
});
var formData = new FormData();
formData.append('cap', blob);
formData.append('file', this.state.imageFile)
axios.post('http://localhost:8080/bottlecap/entry', formData, {headers:{'Content-Type':'multipart/form-data'}})
.then(res=>{
console.log(res.data);
}
This is my fetch sample in Vue3, and it works thanks to you. Thanks!
let formData = new FormData();
formData.append('productJsonData', new Blob([JSON.stringify(productJsonObject)], {type: 'application/json'}));
formData.append('file', image); // This image comes from an <v-file-input> TAG
const response = await fetch(
`http://.../addProduct`,
{
headers: { 'Accept': 'application/json' },
method: 'POST',
body: formData
}
);
const responseData = await response.json();
if (!response.ok) {
console.log('REST error: [' + responseData.error + ']')
throw error;
}

Post request works when use PHP, but it fails with a 500 Internal Error when I use Axios with React, how can I fix that?

I create the following code in PHP:
$url = $API_URL.'/api/v1/courses/'.$COURSE_ID.'/quizzes/'.$QUIZ_ID.'/reports?quiz_report[report_type]=student_analysis&quiz_report[includes_all_versions]=1';
$crl = curl_init();
$headr = array();
$headr[] = 'Content-length: 0';
$headr[] = 'Content-type: application/json';
$headr[] = 'Authorization: Bearer '.$API_KEY;
curl_setopt($crl, CURLOPT_URL, $url );
curl_setopt($crl, CURLOPT_HTTPHEADER,$headr);
curl_setopt($crl, CURLOPT_POST,true);
$rest = curl_exec($crl);
curl_close($crl);
This code works perfectly. Something important that I noticed is if I remove the part "$headr[] = 'Content-length: 0';", the request fails with a 400 Bad Request error.
Now I need to do this with React, I use Axios, this is the code that I use:
var config2 = {
headers: {
'Access-Control-Allow-Origin': '*',
'Authorization': "Bearer 11748~BTNBIfTKrIORcK7SVw09Gryq5bc1MipitSFA4K4Lwh1inbv0jfj5z7mL9U6p1GV3",
'Accept' : 'application/json',
'Content-Length' : '0',
'Content-type' : 'application/json'
}
};
let course_id = '8717'
let quiz_id = '58320'
try {
let url2 = Constantes.URL_PREFIX+'/courses/'+course_id+'/quizzes/'+quiz_id+'/reports?quiz_report[report_type]=student_analysis&quiz_report[includes_all_versions]=1'
const response = await axios.post( url2, config2 )
console.log("xxx - response.data")
console.log(response.data)
} catch(err) {
console.log("ERRO - xxx: "+err)
}
After running the code, I got a 500 internal error.
If I change the following code below
const response = await axios.post( url2, config2 )
to
const response = await axios.get( url2, config2 )
The code works, but I need to run this code using axios.post, just like I do with the PHP code.
The react app does all its requests using a CORS PROXY, I also got an error with
'Content-Length': '0',
when I use the axios.get, the error that I got is
Refused to set unsafe header "Content-Length"
This error doesn't appear when I use axios.post, instead of this error I got the 500 Internal Error.
Any tips to fix this?
I fix the problem using fetch() from javascript.
I simple fetch using post method works for me, don't know it didn't work for Axios.
I think it's a problem from Axios, I'll just post a message later on their Github.

Resources