Uncaught (in promise) ReferenceError: headers is not defined VueJs - javascript

I am using laravel application with Vuejs so I want after a certain process is completed to save the information by hitting the post method endpoint.
In the local environment, it's working perfectly but after I launch the application on Cpanel I am getting this error.
So please someone may help me to figure it out thanks.
let formData = new FormData();
formData.append("series_id", this.series.id);
formData.append("user_id", this.users);
formData.append("transaction_id", response.data.params.transactionId);
formData.append("request_id", response.data.requestId);
formData.append("amount", response.data.params.txAmount);
let url = "https://example.so/api/add-purchase";
axios.post(url, formData, headers).then((response) => {
console.log(response);
if (response.status == 200) {
alert(response.data.message);
window.location.href ="/student/courses";
}
});
this.isLoading = false;

Related

Fetch fails when exceeding a certain execution time even-though using proper CORS headers

I have been stuck with a weird issue with CORS for quite some time now. To explain the setup I have a frontend JS snippet (including fetch API call to my own server) which I want to use as an embed code snippet other web applications can use. (ex: kind of like google analytics)
// JS snippet to copy to an unknown website
<script>
// extract data and add to the body
const extracted_data = {}
fetch("https://api.xxxx.com/xxxxxx/create", {
method: "POST",
mode: 'cors',
body: JSON.stringify(extracted_data),
referrer: "origin",
headers: {
'Content-Type': 'application/json',
},
})
.then(function (response) {
// The API call was successful!
if (response.ok) {
return response.json();
} else {
return Promise.reject(response);
}
})
.then(function (data) {
// This is the JSON from our response
console.warn("Successfull!", data);
alert("Success:" + JSON.stringify(data));
})
.catch(function (err) {
// There was an error
console.warn("Something went wrong ->", err);
alert("error:" + err.message);
});
</script>
The problem is even if I have set my fetch API as below and the correct CORS headers are in my preflight response from my API it works only when the API call resolves immediately. If the API takes more time Fetch throws this common error even if the preflight is successful.
TypeError: Failed to fetch
I verified it using adding the below code to my API. Then it stops working and throws the above error. When I don't have any time taking functions inside my API call it works without errors.
// 10 sec delay to check async behavior of the API
await new Promise(resolve => setTimeout(resolve, 10000));
Any recommendations on how I should proceed to resolve this?

Microsoft Graph API - Error 400 Bad Request when trying to get an access token from code

Im trying to aquire an access token by following this tutorial:
https://learn.microsoft.com/en-us/graph/auth-v2-user
the first request works just fine, but the second request fails with 400 - Bad Request:
net::ERR_ABORTED 400 (Bad Request)
any ideas?
my code currently looks like this:
const getMicrosoftToken = async () => {
if (window.location.href === 'http://localhost:8080/') { location.assign(`http://login.microsoftonline.com/${process.env.VUE_APP_TENANT_ID}/oauth2/v2.0/authorize?client_id=${process.env.VUE_APP_CLIENT_ID}&response_type=code&redirect_uri=${process.env.VUE_APP_REDIRECT_URI}&response_mode=query&scope=offline_access%20chat.readwrite&state=12345`);
} else {
const code = new URLSearchParams(window.location.search).get('code');
const result = await fetch(`http://login.microsoftonline.com/${process.env.VUE_APP_TENANT_ID}/oauth2/v2.0/token?client_id=${process.env.VUE_APP_CLIENT_ID}&scope=chatmessage.send%20chat.readwrite&code=${code}&redirect_uri=${process.env.VUE_APP_REDIRECT_URI}&grant_type=authorization_code`, {
method: 'POST',
mode: 'no-cors'
});
console.log(result);
}
};
im redirecting myself to the authorize request, then i get redirected back to my page with the code parameter,
and finally im trying to make a post request using the code in order to get the token.

HTTP 500 spring web expo image picker

I am trying to upload a file in react native using axios to a spring service backend.
const sf5 = async () => {
let fd = new FormData();
fd.append("file", imgimg.uri)
const eeefile = await instance.post('/uploadfile', {
body: fd
}, {headers:{
"Content-Type": "multipart/form-data"
}}).then(function (response) {
//console.log('~~~~~~~~~~~~~~~' + random_val)
//console.log(response);
});
}
However, spring framework is rejecting the request saying
[dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Current request is not a multipart request]
I tried placing a breakpoint in the spring application class. However, request didnt even reach there.
The am able to upload the file from browser through XHR.
Any pointers would be appreciated.

Unsupported grant type when getting OAuth token for Reddit API

I'm trying to get an OAuth token for the Reddit API following the Application Only OAuth instructions. My reddit app is an installed app, so for my grant_type I'm using https://oauth.reddit.com/grants/installed_client.
Currently I'm running a very short JS script to query the API and get a token:
const APP_ID = 'MY_APP_ID'
const DEVICE_ID = 'TRACKING_ID_20_TO_30_CHARS'
let form = new FormData()
form.append('grant_type', 'https://oauth.reddit.com/grants/installed_client')
form.append('device_id', DEVICE_ID)
fetch('https://www.reddit.com/api/v1/access_token', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${btoa(`${APP_ID}:`)}`,
}),
body: form })
.then(handleResponse)
.then(function(data) {
console.log(data)
})
.catch(error => console.error(error))
function handleResponse(response) {
return response.json()
}
(Note: running the snippet as-is will give you a NetworkError because the APP_ID isn't a real one and I don't want to give mine out.)
The response I get is:
{
"error": "unsupported_grant_type"
}
When I try the same API request using a REST client I get back the expected response, so this makes me think that the problem is JavaScript-related. Since the grant_type matches what the instructions say I'm not really sure what to do with the error. I'm hoping someone else more experienced with OAuth will know what is going on here.
The problem was the use of the FormData object. In earlier stages of troubleshooting I found this answer on Reddit and decided to use it, but that didn't work for me.
It was submitting the data as multipart/form-data rather than application/x-www-form-urlencoded, which Reddit's OAuth server did not like. I wrote a helper function based on this answer which did the trick:
function urlEncode(data) {
let out = [];
for (let key in data) {
out.push(`${key}=${encodeURIComponent(data[key])}`);
}
return out.join('&')
}

Put works in Postman but not AXIOS

This is the weirdest thing in my MERN app. When I do a PUT from Postman to my api it works and updates my api and mongoDB. On the front-end it doesn't update the api even though console logs are showing the correct values and the url is the same? Any help or direction would be appreciated... been playing with it for days now.
POSTMAN PROOF UPDATES WORK
The code for my axios is as follows:
handlePlayerSubmit(id, player) {
console.log('This is the id: ' + id);
console.log('This is the player: ' + player);
let apiUrl = 'http://localhost:3001/api/teams';
//sends the id and new author/text to our api
axios.put(`${apiUrl}/${id}`, player).catch(err => {
console.log(err);
});
}
So I know it's firing due to the console logs... not sure why its not updating the api?
Also it's not console.logging an error.
NETWORK SCREEN SHOT IN DEV TOOLS
HEADERS FROM NETWORK TAB:
This is happening because Axios serializes JavaScript objects to JSON. To serialize in application/x-www-form-urlencoded format you will need to use one of the techniques described in the Axios documentation.
I think qs is a nice solution for you:
let apiUrl = 'http://localhost:3001/api/teams';
//sends the id and new author/text to our api
axios.put(`${apiUrl}/${id}`, qs.stringify(player)).catch(err => {
console.log(err);
});
Axios doesn't like posting plain objects.
One way to workaround issue is with FormData:
let formData = new FormData();
formData.append('param1', 'hi');
formData.append('param2', 'hello');
axios({
method: 'POST',
url: '/api/some-endpoint/',
data: formData
}).then(response => {
console.log(response);
});
https://github.com/axios/axios/issues/1195

Categories

Resources