Put works in Postman but not AXIOS - javascript

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

Related

Axios POST to endpoint, returns OPTIONS request

I am trying to make a post request from a form to an endpoint, the form works fine, and the db too. The main issue is that i am posting to this endpoind localhost:3001/professional with the body of the form as data
export const postPro = (data) => async () =>{
console.log(data)
axios({
method: 'post',
url: "http://localhost:3001/professional",
data: data
})
}
data itself is an object. This is what i get from the console after i press send:
console of backend returning options, I did the first 2 post with postman to see if it works the db, and indeed it does.
I am using Redux toolkits(first time i use it) and React Native
I try rewriting the post, like this:
axios.post("http://localhost:3001/professional", data)
then i try to console.log the data to see if reaches the axios.post and it does, i can see the log of the object data in the console.
Also i was thinking that has something to do with async await so i try to play with that a little, and it's the same result.

Can't find any way to get POST requests working Reddit API - 403 Error

I'm trying to build a reddit-like app on react native, so i'm using axios to fetch requests to Reddit Api and I can't seem to be able to fetch any POST requests, I've tried everything I can, I'm trying to subscribe to a subreddit, here is my request :
subscribe: async function subscribe(action, sub, modhash) {
try {
const token = await this.getAccessToken();
console.log('token: ' + token)
let Headers = {'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json',
'X-Modhash': modhash}
let Params = {'action': action, 'sr_name': sub}
let Body = {'api_type': "json", "extension": "json"}
await axios.post('https://oauth.reddit.com/api/subscribe', Headers, Params, Body)
.then((response) => {
console.log('sub: ' + JSON.stringify(response.data));
console.log("Subbed to " + sub)
})
} catch (error) {
throw 'Could not sub: ' + error
}
},
Here is the Catch result:
"Could not sub: Error: Request failed with status code 403"
here is the official api about subscribe : https://www.reddit.com/dev/api/#POST_api_subscribe
action = "sub" and sr = "t5_2qh03" and I tried sr_name and sr but none seems to work, I'm sure the token is valid since it works with other GET requets I can't find what I did wrong here. Do you guys have any idea on what I'm missing ?
Edit: I've tried the same request with postman and the request actually worked, i did sub to a subreddit, but the same exact request is not working with axios, does my request is okay ?
To me, your code is alright.
However, the Reddit API is such a clusterfuck, that peoples are not much using it.
They are using pupeeter and similar.
For your problem, it all depends of the subreddit, some (many) are not allowing to POST by API at all, of course without warning, or with totally unclear HTTP error codes It just doesn't work.
There is also situations where it works, but only sometimes, or only the first time, or only from an IP of a given allowed country.
They are also widely using black/grey/white listing, shadow banning, and rate limiting. But no notices are ever given. The definition of a clusterfuck.

FETCH/AXIOS DELETE not working with json-server

I know this problem is repeated, but I cannot find the answer to it.
My problem is similar to this one:
Proper Fetch call for Delete using json-server?
I also used fetch and axios both like this:
await axios({
method: 'DELETE',
url: `http://localhost:8000/${measurementData.toolType}?LesionNamingNumber=${measurementData.lesionNamingNumber}`
});
await fetch(`http://localhost:8000/${measurementData.toolType}?lesionNamingNumber=${measurementData.lesionNamingNumber}`, {
method: 'DELETE'
}).then(data => {
console.log('data deleted');
});
I am still getting this error 'DELETE http://localhost:8000/EllipticalRoi?lesionNamingNumber=1 404 (Not Found)'. But I can see the data after visiting this URL.
My react is running on localhost:3000
I am using JSON-server with react.
JSON-SERVER version - 0.16.3
Any suggestions for this problem.

Why does Axios not working with FormData?

I'm using Axios & FormData to send data to a server in a Vue.js project.
It used to work before, but currently, whenever I send a formData object, It doesn't seem to be appended:
Mock server:
Chrome dev tools:
(Notice content-length is 2 and FormData is missing)
let url = "https://benben.free.beeceptor.com/1"
const fd = new FormData()
fd.append('key', 'value')
return axios.post(url, fd, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
Things I've tried:
Look for the payload in: chrome/firefox/edge dev tools & in a mock server.
Send simple JSON instead of FormData - it works.
Send with and without the header - doesn't change anything.
Check if the data is appended to FormData successfully - it is (key-value exists).
Tried other Stackoverflow solutions. Nothing worked so far.
Updating axios.
Using the direct axios API (passing an object to axios).
Note: I need FormData, because I need to upload a file.
Let me know if any other code samples would be helpful.
Thanks in advance!
I've figured it out - I'm using snakecaseKeys package to manipulate the data before sending. It seems not to play well with FormData objects.
import snakecaseKeys from 'snakecase-keys'
axios.defaults.transformRequest = [(data) => {
if (data) {
return snakecaseKeys(data, { deep: true })
}
}, ...axios.defaults.transformRequest]
Thanks for the comments guys!
In case anyone else runs into this issue, you can side-step the transformations in you transformRequest using instanceof.
transformRequest: [
(data) => {
if (data instanceof FormData) return data;
// otherwise, transform your data
return transformedData;
},
],
in React the form should also have encType="multipart/form-data" attribute, may be in vue also?

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('&')
}

Categories

Resources