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.
Related
I made a POST request to get a QRCode
Here is the data I get from the response. The preview of the response works fine only I don't know how to use this data to display it in a tag on my html page for example. Any ideas?
It finally works as : (in async function)
const response = await fetch(URL_FOR_QRCODE, //your own url
{
method: "POST", //because my endpoint is a post method
credentials: 'include' //because I use cookies (its a auth qr code)
});
this.QRCodeSRC = URL.createObjectURL(await response.blob());
I am trying to return a response from a backend server, of technologies that match a specific url which is searched on the front end.
My form will submit, and the URL will change, but no results will come through, and no errors appear in the console.
My front end script tag is as follows:
function Submit () {
e.preventDefault();
const formResult = new FormData(form);
const url = '/' + encodeURIComponent(formResult.get('search'));
const button = document.getElementById('search');
const sendHttpsRequest = (method, url, data) => {
return fetch(url, {
method: method,
body: JSON.stringify(data),
headers: data ? {'Content-Type': 'application/json'} : {}
}).then(response => {
if (response.status >= 400) { //response okay
return response.json().then(errResData => {
const error = new Error('Something went wrong');
error.data = errResData;
throw error;
});
}
return response.json();
});
};
const getData = () => {
sendHttpsRequest('GET', '/:url').then(responseData => {
console.log(responseData);
});
};
button.addEventListener('search', getData);
}
Is there something here I am missing? I think it might be a function call, but do I also need to include a function call when I am sending an HTTP request? Where would the function call go in this case? What would it look like?
You have lots of problems with this.
You call getData when a button is clicked, but only if that button is clicked after Search is called. You never call Search.
The first thing Search does is call e.preventDefault, but e isn't defined anywhere.
You create formResult from a variable called form which you never define
You create formResult when Submit is called but it looks more like something you want to do when getData is called
You set the body of the request with JSON.stringify(data), but you've never defined data … and if you intended to say formResult then that would be a FormData object which won't convert to JSON.
When you send the request you sent it to '/:url' which uses Express parameter syntax … but this is the client-side code so you need to put the actual data there.
You define a variable url in Submit but then you never use it (probably you intended to use it in 6 but forgot and hardcoded a string that didn't make sense instead).
You are trying to set a body on a GET request
You seem to have thrown a lot of code together without testing it as you went along.
I recommend starting from scratch.
Write a function to be called when you click the button. Have it just prevent the default behaviour and log something to the console.
Then fetch the form data you want and log that.
Continue to work from there, testing each stage as you go along so you can detect the mistakes like these.
I am trying to replay a request to another instance of my API, so I am making a POST request as shown below. This works fine except for the fact that the data (JSON.stringify(req.body)) is not being passed. req.body on the other instance returns a blank map {} even though I have confirmed that JSON.stringify(req.body) returns what I expect. Is there something wrong with how I am passing the data with the POST request? Thanks in advance for any help.
var betaReq = https.request({
hostname: 'some-product-beta.cloudfunctions.net',
path: '/intercomEventsReplayed',
method: 'POST',
headers: {
'x-hub-signature': req.headers['x-hub-signature']
}
});
betaReq.write(JSON.stringify(req.body));
betaReq.end();
I am building a web app with Django/Python and trying to send data to a controller via a POST request using the Axios library (within Vue.js code).
The POST QueryDict seems to be empty and I can't see why that is happening:
changeCountry: function(e, id){
console.log("Let's change the country")
console.log(e.target.value) // is printing correctly
console.log(id) // also printing correctly
axios({
method: 'post',
url: '/template/country',
data: {
id: id,
country: e.target.value
},
headers: {
'X-CSRFToken': "{{csrf_token}}"
}
})
.then(function (response) {
alert(response.data); // this is returning what I expect
})
.catch(function (error) {
console.log(error);
})
},
The Python method looks like this:
def update_template_country(request):
pprint(request.POST) # prints an empty QueryDict
id = request.POST.get('id')
country = request.POST.get('country')
print(id, country) #prints None None
return HttpResponse("The country is changed") # this is being returned back to the client
The console.log messages at the top print what I expect and since there is no error I am assuming the CSRF header token is fine. Have I missed something obvious or misunderstood how this is working?
EDIT: looking at the Chrome Network tab, it seems the data is being 'POSTed' correctly:
It shows this:
{"id":"593ff2270098e6e8d3292b60","country":"US"}
and that's what I expect, so I suspect the issue is with Django. But I can't see what that might be.
Write your python POST request like this:
def update_template_country(request):
data = json.loads(request.body)
id = data["id"]
country = data["country"]
'''Any other function you want to perform'''
return HttpResponse(json.dumps({'message':'The country is changed'},status=200)
Basically the problem is with the format of POST request, Django is not able to parse it properly that's why when you print the POST request it return an empty dictionary.
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