I'm using fetch to send value to my server. my server is php.
when I send my values with postman my server response as well.
but when I want to send my values with fetch I cannot get them from server side.
postman:
my requestOption:
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(parms)
};
my values sent to server but I cannot get them like postman form-data.
parms is a object variable. like:
var parms = {};
parms['tok'] = '35345345';
Just use formData as fetch body:
var formData = new FormData()
formData.append("tok", '35345345')
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json'
},
body: formData
};
Related
I have a function which uses Axios to send a POST request which goes through successfully and I get the right response. Now I want to try using fetch to do the exact same POST request. Unfortunately, the fetch request returns a 415 Unsupported Media Type response error and I have no idea why.
Currently:
onBeforeUnload = () => {
try {
const defaultPresence = {
presence: 'AVAILABLE',
message: '',
};
const url = getServerURL() + urls.PRESENCE;
axios.post(
url,
defaultPresence,
{
headers: {
Authorization: `Bearer ${getAccessToken()}`,
},
},
);
} catch (error) {
console.log(error);
}
}
The fetch code I've used to replace the Axios POST request.
fetch(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${getAccessToken()}`,
},
body: defaultPresence,
});
fetch does not recognise plain objects as the body.
If you want to send JSON then you need to encode the data and set the content-type header yourself.
fetch(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${getAccessToken()}`,
"Content-Type": "application/json",
},
body: JSON.stringify(defaultPresence),
});
I am working on React web app with a Flask backend. how can I send a file with JSON data on the body?
I try the code below but is not working
const file = e.target.file[0]
const user = [{name: 'Ma'}]
const formData = new FormData()
dormData.append('file', file)
dormData.append('user', user)
const post = await axios({
method: 'post',
url: 'http://127.0.0.1:5000/route',
data: formData,
headers: { "Content-Type": "multipart/form-data" }
})
You have to set the Content-Type header as application/json and you can set the body as your json
Your code would look something like this
const post = await axios({
method: 'post',
url: 'http://127.0.0.1:5000/route',
headers: { "Content-Type": "application/json" },
body: JSON.stringify(myJson) //insert your stringified json here
})
Since you are creting a react web app, it's easy to structure a JSON from a form.
You are spelling formData wrong. Use this code:
formData.append('file', file)
formData.append('user', user)
I am new to front end dev. How can I set "application/json" content-type and gzip content-encoding in the fetch call in locally run React code?
const data = await fetch(url, {
method: 'post',
body: body,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json' // this does not work when run locally
}
});
You could try this
const data = await fetch(url, {
method: 'post',
body: JSON.stringify(body), // this will encode body to string, assuming it's an Object
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});
but I'm not sure what do you want with "gzip content-encoding". If the console prints any errors, they can be helpful too
I am running nodeJS and have the following function:
const fetch = require("node-fetch");
async function createCustomer() {
let response = await fetch('https://sampleurl.com/login', {
method: 'POST',
body: 'username=usernameHere&password=passwordHere',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json, text/plain, */*'
}
});
tempVar = await response.json();
console.log(tempVar);
This logs in and authenticates, providing me a successful response.
However if I then try and do the next step, it fails with an unauthorized error.
let response2 = await fetch('https://sampleurl.com/list', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json, text/plain, */*'
}
});
tempVar2 = await response2.json();
console.log(tempVar2);
In python I use requests.Session() and do the initial authorization and then any API call after that just begins with 'session' and it works. For example::
session = requests.Session()
session.post('https://sampleurl.com/login',data={'username':'usernameHere','password':'passwordHere'})
response = session.get('https://sampleurl.com/list').json()
print(response)
This is the functionality I am trying to replicate, but I can't figure out how to store the session.
Any help would be much appreciated.
Edit: Using Express.
Edit2: This is not hitting an API I am running the server for, I am not looking for how to build this feature as the API server, rather just connect to an external API.
Why my code in js dont sends the post data and in python works ?
In js
const options = {
url: "https://asd.com",
method: 'POST',
headers: {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
'User-Agent': 'my-reddit-client',
'data': {"user.login":"login","user.senha":"pass"}
}
};
request(options, function(err, resx, body) {
console.log(resx);
res.send(body)
});
In python
import requests
data = {
"user.login":"login",
"user.senha":"pass"
}
r = requests.post('https://asd.com', params=data)
print(r.text)
I just want to send a custom form without json format, but it never works.
to make POST request in vanilla JS:
fetch("https://asd.com", {
method: 'POST',
body: {"user.login":"login","user.senha":"pass"},
headers: {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
'User-Agent': 'my-reddit-client',
}
}).then(res => res.json())
I suggest you also to read about the fetch API so It won't be hard for you anymore to make any other kind of request in JS https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch.