add parameters to a post request in js [duplicate] - javascript

This question already has answers here:
How can I pass POST parameters in fetch request? - React Native
(2 answers)
Closed 1 year ago.
I need to add some parameters to this request:
fetch(url_ticket, {
//body: JSON.stringify(data),
//mode: 'no-cors',
param: {
'token': `${token}`,
'id': `${id}`,
'id_secret': `${id_secret}`
},
method: 'POST'
})
.then(response => {
console.log(response.text());
})
.catch(error => {
console.error(error);
});
However, I'm getting an error. I've made that request in Postman an it works, so the problem is obviously in this code. I think the error is in the params parameter; how can I add properly parameters in this request?
I'm literally new to js, i've searched for answers but i can't understand a thing, so posting my real problem has been my last option

Here is the code to send post request with parameter
const data = { username: 'example' };
fetch('https://example.com/profile', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
For info you can read doc here Using fetch

I think this SO answer is a nice and clean way to do it. Basically, it constructs the URL string with parameters.
fetch(url_ticket + new URLSearchParams({
token: `${token}`,
id: `${id}`,
id_secret: `${id_secret}`
}), {});
You could also construct the parameters in a more manual way, by inserting the variables into a backticked URL string:
let url = `${url_ticket}?token=${token}&id=${id}&id_secret=${id_secret}`;
fetch(url, {...})

Related

Fetch data from api with graphql [duplicate]

This question already has answers here:
How to call GraphQL API from Node.js/Express server?
(2 answers)
Closed 2 years ago.
I am trying to connect to a website and they have given me :
Url: https://api.demo...
headers:"x-api-key" and "x-api-user"
I do not know how to make the connection with them,I tried the code below:
const query = `
query {
some query here
}
`;
const url = ``
const opts = {
method: "POST",
headers: { "x-api-key": ,
"x-api-user": , },
body: JSON.stringify({ query })
};
Is this the right way? when I run it npm start=> App Crashes I am new to javascript and I dont even know how to make the search in google,can someone please guide me to a tutorial,link or please respond with the right way?
Thank you for your understanding
You can do it using the fetch call.
const query = `query {
Some query
}`;
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query
})
})
.then(r => r.json())
.then(data => console.log('data returned:', data));

How to post file data to Gitlab project using JavaScript fetch [duplicate]

I'm trying to POST a JSON object using fetch.
From what I can understand, I need to attach a stringified object to the body of the request, e.g.:
fetch("/echo/json/",
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify({a: 1, b: 2})
})
.then(function(res){ console.log(res) })
.catch(function(res){ console.log(res) })
When using jsfiddle's JSON echo I'd expect to see the object I've sent ({a: 1, b: 2}) back, but this does not happen - chrome devtools doesn't even show the JSON as part of the request, which means that it's not being sent.
With ES2017 async/await support, this is how to POST a JSON payload:
(async () => {
const rawResponse = await fetch('https://httpbin.org/post', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({a: 1, b: 'Textual content'})
});
const content = await rawResponse.json();
console.log(content);
})();
Can't use ES2017? See #vp_art's answer using promises
The question however is asking for an issue caused by a long since fixed chrome bug.
Original answer follows.
chrome devtools doesn't even show the JSON as part of the request
This is the real issue here, and it's a bug with chrome devtools, fixed in Chrome 46.
That code works fine - it is POSTing the JSON correctly, it just cannot be seen.
I'd expect to see the object I've sent back
that's not working because that is not the correct format for JSfiddle's echo.
The correct code is:
var payload = {
a: 1,
b: 2
};
var data = new FormData();
data.append( "json", JSON.stringify( payload ) );
fetch("/echo/json/",
{
method: "POST",
body: data
})
.then(function(res){ return res.json(); })
.then(function(data){ alert( JSON.stringify( data ) ) })
For endpoints accepting JSON payloads, the original code is correct
I think your issue is jsfiddle can process form-urlencoded request only. But correct way to make json request is pass correct json as a body:
fetch('https://httpbin.org/post', {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({a: 7, str: 'Some string: &=&'})
}).then(res => res.json())
.then(res => console.log(res));
From search engines, I ended up on this topic for non-json posting data with fetch, so thought I would add this.
For non-json you don't have to use form data. You can simply set the Content-Type header to application/x-www-form-urlencoded and use a string:
fetch('url here', {
method: 'POST',
headers: {'Content-Type':'application/x-www-form-urlencoded'}, // this line is important, if this content-type is not set it wont work
body: 'foo=bar&blah=1'
});
An alternative way to build that body string, rather then typing it out as I did above, is to use libraries. For instance the stringify function from query-string or qs packages. So using this it would look like:
import queryString from 'query-string'; // import the queryString class
fetch('url here', {
method: 'POST',
headers: {'Content-Type':'application/x-www-form-urlencoded'}, // this line is important, if this content-type is not set it wont work
body: queryString.stringify({for:'bar', blah:1}) //use the stringify object of the queryString class
});
After spending some times, reverse engineering jsFiddle, trying to generate payload - there is an effect.
Please take eye (care) on line return response.json(); where response is not a response - it is promise.
var json = {
json: JSON.stringify({
a: 1,
b: 2
}),
delay: 3
};
fetch('/echo/json/', {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: 'json=' + encodeURIComponent(JSON.stringify(json.json)) + '&delay=' + json.delay
})
.then(function (response) {
return response.json();
})
.then(function (result) {
alert(result);
})
.catch (function (error) {
console.log('Request failed', error);
});
jsFiddle: http://jsfiddle.net/egxt6cpz/46/ && Firefox > 39 && Chrome > 42
2021 answer: just in case you land here looking for how to make GET and POST Fetch api requests using async/await or promises as compared to axios.
I'm using jsonplaceholder fake API to demonstrate:
Fetch api GET request using async/await:
const asyncGetCall = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const data = await response.json();
// enter you logic when the fetch is successful
console.log(data);
} catch(error) {
// enter your logic for when there is an error (ex. error toast)
console.log(error)
}
}
asyncGetCall()
Fetch api POST request using async/await:
const asyncPostCall = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
// your expected POST request payload goes here
title: "My post title",
body: "My post content."
})
});
const data = await response.json();
// enter you logic when the fetch is successful
console.log(data);
} catch(error) {
// enter your logic for when there is an error (ex. error toast)
console.log(error)
}
}
asyncPostCall()
GET request using Promises:
fetch('https://jsonplaceholder.typicode.com/posts')
.then(res => res.json())
.then(data => {
// enter you logic when the fetch is successful
console.log(data)
})
.catch(error => {
// enter your logic for when there is an error (ex. error toast)
console.log(error)
})
POST request using Promises:
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
// your expected POST request payload goes here
title: "My post title",
body: "My post content."
})
})
.then(res => res.json())
.then(data => {
// enter you logic when the fetch is successful
console.log(data)
})
.catch(error => {
// enter your logic for when there is an error (ex. error toast)
console.log(error)
})
GET request using Axios:
const axiosGetCall = async () => {
try {
const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts')
// enter you logic when the fetch is successful
console.log(`data: `, data)
} catch (error) {
// enter your logic for when there is an error (ex. error toast)
console.log(`error: `, error)
}
}
axiosGetCall()
POST request using Axios:
const axiosPostCall = async () => {
try {
const { data } = await axios.post('https://jsonplaceholder.typicode.com/posts', {
// your expected POST request payload goes here
title: "My post title",
body: "My post content."
})
// enter you logic when the fetch is successful
console.log(`data: `, data)
} catch (error) {
// enter your logic for when there is an error (ex. error toast)
console.log(`error: `, error)
}
}
axiosPostCall()
I have created a thin wrapper around fetch() with many improvements if you are using a purely json REST API:
// Small library to improve on fetch() usage
const api = function(method, url, data, headers = {}){
return fetch(url, {
method: method.toUpperCase(),
body: JSON.stringify(data), // send it as stringified json
credentials: api.credentials, // to keep the session on the request
headers: Object.assign({}, api.headers, headers) // extend the headers
}).then(res => res.ok ? res.json() : Promise.reject(res));
};
// Defaults that can be globally overwritten
api.credentials = 'include';
api.headers = {
'csrf-token': window.csrf || '', // only if globally set, otherwise ignored
'Accept': 'application/json', // receive json
'Content-Type': 'application/json' // send json
};
// Convenient methods
['get', 'post', 'put', 'delete'].forEach(method => {
api[method] = api.bind(null, method);
});
To use it you have the variable api and 4 methods:
api.get('/todo').then(all => { /* ... */ });
And within an async function:
const all = await api.get('/todo');
// ...
Example with jQuery:
$('.like').on('click', async e => {
const id = 123; // Get it however it is better suited
await api.put(`/like/${id}`, { like: true });
// Whatever:
$(e.target).addClass('active dislike').removeClass('like');
});
Had the same issue - no body was sent from a client to a server.
Adding Content-Type header solved it for me:
var headers = new Headers();
headers.append('Accept', 'application/json'); // This one is enough for GET requests
headers.append('Content-Type', 'application/json'); // This one sends body
return fetch('/some/endpoint', {
method: 'POST',
mode: 'same-origin',
credentials: 'include',
redirect: 'follow',
headers: headers,
body: JSON.stringify({
name: 'John',
surname: 'Doe'
}),
}).then(resp => {
...
}).catch(err => {
...
})
This is related to Content-Type. As you might have noticed from other discussions and answers to this question some people were able to solve it by setting Content-Type: 'application/json'. Unfortunately in my case it didn't work, my POST request was still empty on the server side.
However, if you try with jQuery's $.post() and it's working, the reason is probably because of jQuery using Content-Type: 'x-www-form-urlencoded' instead of application/json.
data = Object.keys(data).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(data[key])).join('&')
fetch('/api/', {
method: 'post',
credentials: "include",
body: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
The top answer doesn't work for PHP7, because it has wrong encoding, but I could figure the right encoding out with the other answers. This code also sends authentication cookies, which you probably want when dealing with e.g. PHP forums:
julia = function(juliacode) {
fetch('julia.php', {
method: "POST",
credentials: "include", // send cookies
headers: {
'Accept': 'application/json, text/plain, */*',
//'Content-Type': 'application/json'
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" // otherwise $_POST is empty
},
body: "juliacode=" + encodeURIComponent(juliacode)
})
.then(function(response) {
return response.json(); // .text();
})
.then(function(myJson) {
console.log(myJson);
});
}
It might be useful to somebody:
I was having the issue that formdata was not being sent for my request
In my case it was a combination of following headers that were also causing the issue and the wrong Content-Type.
So I was sending these two headers with the request and it wasn't sending the formdata when I removed the headers that worked.
"X-Prototype-Version" : "1.6.1",
"X-Requested-With" : "XMLHttpRequest"
Also as other answers suggest that the Content-Type header needs to be correct.
For my request the correct Content-Type header was:
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
So bottom line if your formdata is not being attached to the Request then it could potentially be your headers. Try bringing your headers to a minimum and then try adding them one by one to see if your problem is resolved.
If your JSON payload contains arrays and nested objects, I would use URLSearchParams and jQuery's param() method.
fetch('/somewhere', {
method: 'POST',
body: new URLSearchParams($.param(payload))
})
To your server, this will look like a standard HTML <form> being POSTed.
You could do it even better with await/async.
The parameters of http request:
const _url = 'https://jsonplaceholder.typicode.com/posts';
let _body = JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1,
});
const _headers = {
'Content-type': 'application/json; charset=UTF-8',
};
const _options = { method: 'POST', headers: _headers, body: _body };
With clean async/await syntax:
const response = await fetch(_url, _options);
if (response.status >= 200 && response.status <= 204) {
let data = await response.json();
console.log(data);
} else {
console.log(`something wrong, the server code: ${response.status}`);
}
With old fashion fetch().then().then():
fetch(_url, _options)
.then((res) => res.json())
.then((json) => console.log(json));
**//POST a request**
const createTodo = async (todo) => {
let options = {
method: "POST",
headers: {
"Content-Type":"application/json",
},
body: JSON.stringify(todo)
}
let p = await fetch("https://jsonplaceholder.typicode.com/posts", options);
let response = await p.json();
return response;
}
**//GET request**
const getTodo = async (id) => {
let response = await fetch('https://jsonplaceholder.typicode.com/posts/' + id);
let r = await response.json();
return r;
}
const mainFunc = async () => {
let todo = {
title: "milan7",
body: "dai7",
userID: 101
}
let todor = await createTodo(todo);
console.log(todor);
console.log(await getTodo(5));
}
mainFunc()
I think that, we don't need parse the JSON object into a string, if the remote server accepts json into they request, just run:
const request = await fetch ('/echo/json', {
headers: {
'Content-type': 'application/json'
},
method: 'POST',
body: { a: 1, b: 2 }
});
Such as the curl request
curl -v -X POST -H 'Content-Type: application/json' -d '#data.json' '/echo/json'
In case to the remote serve not accept a json file as the body, just send a dataForm:
const data = new FormData ();
data.append ('a', 1);
data.append ('b', 2);
const request = await fetch ('/echo/form', {
headers: {
'Content-type': 'application/x-www-form-urlencoded'
},
method: 'POST',
body: data
});
Such as the curl request
curl -v -X POST -H 'Content-type: application/x-www-form-urlencoded' -d '#data.txt' '/echo/form'
You only need to check if response is ok coz the call not returning anything.
var json = {
json: JSON.stringify({
a: 1,
b: 2
}),
delay: 3
};
fetch('/echo/json/', {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: 'json=' + encodeURIComponent(JSON.stringify(json.json)) + '&delay=' + json.delay
})
.then((response) => {if(response.ok){alert("the call works ok")}})
.catch (function (error) {
console.log('Request failed', error);
});
// extend FormData for direct use of js objects
Object.defineProperties(FormData.prototype, {
load: {
value: function (d) {
for (var v in d) {
this.append(v, typeof d[v] === 'string' ? d[v] : JSON.stringify(d[v]));
}
}
}
})
var F = new FormData;
F.load({A:1,B:2});
fetch('url_target?C=3&D=blabla', {
method: "POST",
body: F
}).then( response_handler )
you can use fill-fetch, which is an extension of fetch. Simply, you can post data as below:
import { fill } from 'fill-fetch';
const fetcher = fill();
fetcher.config.timeout = 3000;
fetcher.config.maxConcurrence = 10;
fetcher.config.baseURL = 'http://www.github.com';
const res = await fetcher.post('/', { a: 1 }, {
headers: {
'bearer': '1234'
}
});

How to post a x-www-form-urlencoded data properly using javascript? [duplicate]

This question already has answers here:
How do I POST a x-www-form-urlencoded request using Fetch?
(17 answers)
Closed 4 years ago.
I have written a JS function to post categoryId and shopId and page:0 to an api and this is my funciton :-
getInsideMenu(categoryid,shopid){
var formBody = [];
var details={
'categoryId':categoryid,
'shopId':shopid ,
'page':'0'
};
for (var property in details) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
return fetch(
`${serverAddress}/api/shopProducts`,
{
method: 'POST',
body: formBody,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
).then((res)=>(res.json()))
},
But I'm getting null .I suppose the function is not defined properly. What can be done to fix it. It works well in POSTMAN.
[![this is in postman how I send][1]][1]
You're building an array of encoded name/value pairs and passing that directly as the body of the POST. But fetch doesn't accept an array in that parameter.
The minimal change to your code would be to join the array using & as the separator:
return fetch(
`${serverAddress}/api/shopProducts`,
{
method: 'POST',
body: formBody.join("&"), // <===== here
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
). /* etc */
Alternately, use FormData, as this is exactly what it's for: :-)
getInsideMenu(categoryid,shopid){
var formBody = new FormData();
formBody.set("categoryId", categoryid);
formBody.set("shopId", shopid);
formBody.set("page", "0");
return fetch(
`${serverAddress}/api/shopProducts`,
{
method: 'POST',
body: formBody,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
).then((res)=>(res.json()));
}
(Depending on your needs, you might use set or append. The above uses set.)
Side note 1:
This line:
).then((res)=>(res.json()));
...doesn't need most of those ():
).then(res => res.json());
Side note 2:
Don't forget to check for success; failing to do so is a common pitfall when using fetch. fetch doesn't reject on HTTP error (like 404 or 500). If you want to reject on HTTP error, you have to do it yourself:
return fetch(/*...*/)
.then(res => {
if (!res.ok) {
throw new Error(res.status);
}
return res;
})
.then(res => res.json());
Read this answer
You have to insert at least formBody = formBody.join("&"); after the loop.

posting form data with Axios to .NET API

I'm using React and Axios to post formData to an internal .NET API.
The API is expecting data like this:
[HttpPost("upload")]
public virtual async Task<IActionResult> PostMulti(Int64 parentId, ICollection<IFormFile> fileData)
{
foreach (var file in fileData) {
await SaveFile(file, parent);
}
return Created("", Map(Repository.Get(parentId)));
}
When I step through the debugger, the count for "fileData" is always 0.
Here is how I'm sending it using Axios:
const formData = new FormData();
formData.append('image', this.state.file);
console.log("this.state.file = ", this.state.file);
console.log("formData = ", formData);
axios({
url: `/api/gameMethods/playerStates/${this.props.playerId}/files/upload`,
method: 'POST',
data: formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
}
})
.then((response) => {
//handle success
console.log('response -- then: ', response);
this.setState({
file: this.state.file
});
})
.catch((response) => {
//handle error
console.log('response -- catch: ', response);
});
I use console.log for debugging. It shows me the file object when I write it out(name, size, etc).
It also fires in the ".then" handler of the method and shows this:
"response -- then: data: Array(0), status: 201, statusText: "Created"
"
So, I have no idea why it's not sending anything to the API and I don't really know what's happening or how to fix this problem.
Any help would be greatly appreciated.
Thanks!
You should post array of the formData
const filesToSubmit = []
filesToSubmit.push((new FormData()).append('image', this.state.file))
and while posting the data the property name should be formData
axios({
url: `/api/gameMethods/playerStates/${this.props.playerId}/files/upload`,
method: 'POST',
data: {formData : filesToSubmit},
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
}
})
If there is an issue with constructing an array you need to add IFormFile properties to the array
So I had exactly the same issue, whereby no matter which way I twisted the FormData object and regardless of the headers I sent, I couldn't get .NET to accept the submission.
From the Node.js side, it was difficult to actually inspect the HTTP call issued by Axios - meaning I couldn't see what I was actually POSTing.
So I moved the POST to the UI for some debugging, and found that the FormData payload was not being passed as I was expecting, so it was proper that .NET was rejecting.
I ended up using the configuration below, and the POSTs began going through. Again, in my case, I thought I needed FormData, but the below was simple enough:
axios({
url: myUrl,
method: 'POST',
data: `email=${myEmail}`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});
Update: Not sure how encoded data will work, but since it'll be passed as a string, it's worth a shot!
const myUploadedImage = "data:image/png;name=colors.png;base64,iVBORw0KGgoAAAANSUhEUgAAA5gAAAEECAIAAADCkQz7AAAGGUlEQVR4nO3YIY/IcRzHcWd4AjZJkZQr2I1dIJlyRU5ErkJggg=="

GitHub API - Comment on Gist returns 404

After following the documentation on GitHub's API, I got stuck on submitting a comment for a gist, the following code always returns 404, and the same call made in Postman too.
My JavaScript code as follows:
const config = {
method: 'POST',
headers: {
'Authorization': credentials.authorizationHeader,
'Content-Type': 'application/vnd.github.v3.text+json'
},
body: { "body": JSON.stringify(comment) }
};
fetch(`https://api.github.com/gists/${gistId}/comments/`, config)
.then(res => {
if (res.ok) {
dispatch(getGistDetails(gistId, credentials));
dispatch({ type: SUBMIT_COMMENT_SUCCESS });
} else {
ToastAndroid.show('An error ocurred, please try again.', ToastAndroid.SHORT);
console.log(res);
dispatch({ type: SUBMIT_COMMENT_FAIL });
}
})
.catch(err => console.log(err));
Credentials I'm getting via OAuth:
accessToken: "redacted"
authorizationHeader:"bearer redacted"
clientID:"redacted"
idToken:null
scopes:"gist"
type:"bearer"
I tried changing the authorizationHeader to token <oauth_token, but still no success.
Thanks in advance.
Looks like you have some non standard characters in your GIST ID that are not even visible and I can't even get your link to work ( or is it private? )
Turns out I was overcomplicating, as getting a gist's details through the API also nets you a comments_url field with the correct url, so no need to splice strings, falling into the very strange issue mentioned by #Zilvinas below. Also, a minor adjustment in the body to
const body = { body: comment }
const config = {
method: 'POST',
headers: {
'Authorization': credentials.authorizationHeader,
'Content-Type': 'application/vnd.github.v3.text+json'
},
body: JSON.stringify(body)
};
fixed the subsequent Problems parsing JSON error I got.

Categories