Premature end of file error in XML Request - javascript

for some reason I am getting this error when trying to create a simple login request to Salesforce.
This works exactly as it should in postman, however, when I try and convert to Google Apps Script it seems to create a "Premature end of file" error.
var myHeaders = {
"Content-Type": 'text/xml',
SOAPAction: '/',
Cookie: "BrowserId=sB-PspOVEeqEttdm-K56tw",
}
/*myHeaders.append("Content-Type", "text/xml");
myHeaders.append("SOAPAction", "\"\"");
myHeaders.append("Cookie", "BrowserId=sB-PspOVEeqEttdm-K56tw");*/
var raw = "<Envelope xmlns=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <Header>\n </Header>\n <Body>\n <login xmlns=\"urn:enterprise.soap.sforce.com\">\n <username>xx#xx.com</username>\n <password>xx</password>\n </login>\n </Body>\n</Envelope>";
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow',
muteHttpExceptions : true
};
var response = UrlFetchApp.fetch("https://test.salesforce.com/services/Soap/c/48.0/", requestOptions)
//.then(response => response.text())
//.then(result => logger.log(result))
//.catch(error => logger.log('error', error));
Logger.log(response.getContentText())```

How about this modification?
Modification points:
I think that in this case, Cookie: "BrowserId=sB-PspOVEeqEttdm-K56tw" might not be required.
The properties of body and redirect are not included in the arguments of UrlFetchApp.fetch.
Modified script:
var myHeaders = {
SOAPAction: '/',
}
var raw = "<Envelope xmlns=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <Header>\n </Header>\n <Body>\n <login xmlns=\"urn:enterprise.soap.sforce.com\">\n <username>xx#xx.com</username>\n <password>xx</password>\n </login>\n </Body>\n</Envelope>";
var requestOptions = {
method: 'POST',
headers: myHeaders,
contentType: "text/xml",
payload: raw,
muteHttpExceptions : true
};
var response = UrlFetchApp.fetch("https://test.salesforce.com/services/Soap/c/48.0/", requestOptions);
Logger.log(response.getContentText())
Note:
In this modification, it supposes that the values of SOAPAction, raw and https://test.salesforce.com/services/Soap/c/48.0/ are correct.
Reference:
fetch(url, params)

Related

Why is this not working? (fetch()/ getJSON() from WIX)

I have written the following code to access the companies house api (https://developer.company-information.service.gov.uk/). I have googled and tried many things and I have no idea how to get data from this api using fetch/ getJSON. Please help. I am new to javascript.
import { getJSON } from 'wix-fetch';
const baseURL = "https://api.companieshouse.gov.uk"
export function call_companieshouse_api(endpt, search_param){
var api_key = btoa(key)
var url = baseURL + endpt + search_param
getJSON(url, {
method: 'get',
headers: {"Authorization": "Basic " + api_key,
"Content-Type": "application/json",
"Accept": "application/json"},
credentials: "include",
mode: "cors"
})
.then(json => console.log(json.someKey))
.catch(err => console.log(err));
}
I've managed to make it work!
I'm not exactly sure how, but I will explain what I have done (apart from the obvious code change).
I created a new backend file .jsw and in this file is the following code.
import {fetch} from 'wix-fetch';
import btoa from 'btoa'
const baseURL = 'https://api.companieshouse.gov.uk';
var api_key = 'the api key';
export function call_companieshouse_api(endpt, search_param){
var url = baseURL + endpt + search_param;
var base64_key = btoa(api_key)
return fetch(url, {
method: 'GET',
headers: {'Authorization': 'Basic ' + base64_key,
'Content-Type': 'application/json',
'Accept': 'application/json'},
credentials: 'include',
mode: "cors"
}).then(response => response.json());
}
I then have a button click event function with the following code.
export function button1_click(event) {
var search_param = $w('#input1').value;
if (search_param.length <= 1) {
$w('#box1').show();
return;
}
var endpt = "/search/companies?q="
call_companieshouse_api(endpt, search_param)
.then(data => {
console.log(data);
});
}

Same Request, Different Results. (Chrome Extension vs Chrome Browser)

I am currently working on a Chrome Extension. Because I was expecting difficulties, I made a beta Version in HTML & JS, sending request to a PHP script, which is working as expected.
Although I simply copied and pasted my code (with some small changes due to the nature of Chrome Extensions) it's not working anymore. The request is type JSON and includes priv_key and lv_number (and their key values).
The same request in the Beta yields different results in the Extension itself.
SNIPPET OF BETA REQUEST
function getFormData(data2submit) {
event.preventDefault(); //Prevents Reload
const status = document.getElementById("status"); // <p> to show status
status.innerHTML="Request Sent";
//get data that we need for the .json
var privateKey = document.getElementById("PRIV-Key").value;
var lv_number = document.getElementById("LV-Number").value;
//create .json
var formData = {
"priv_key": privateKey,
"lv_number": lv_number
}
//send data to sendFormData function
sendFormData(JSON.stringify(formData));
}
function sendFormData(formData) {
//function to send and receive data (and populate fields lateron)
async function postData(formData) {
const response = await fetch("http://localhost/learneasy_js/lCheck3.php", {
method: 'POST',
mode: "same-origin",
credentials: "same-origin",
headers: {
'Content-Type': 'application/json'
},
referrer: 'no-referrer',
body: formData
});
const json = await response.json();
}
postData(formData);
}
SNIPPET OF EXTENSION REQUEST
function sendRequest() {
chrome.storage.sync.get(['key'], function(result) {
privKey = deobfuscate(result.key);
});
chrome.storage.sync.get(['lvnr'], function(result) {
lvnr = result.lvnr;
});
var formData = {
"priv_key": privKey,
"lv_number": lvnr
}
formData = JSON.stringify(formData);
async function postData(formData) {
const response = await fetch("http://localhost/learneasy_js/lCheck3.php", {
method: 'POST',
mode: "cors",
credentials: "same-origin",
headers: {
'Content-Type': 'application/json'
},
referrer: 'no-referrer',
body: formData
});
const json = await response.json();
setInfo(json);
}
postData(formData);
}
I have compared the output of both bodies (formData) and they are, as far as I can see, equal.
The problem is that chrome.storage.sync.get is asynchronous which means that you're using the privKey and lvnr variables before they are set to the values in storage, here is how you can fix that:
function sendRequest() {
chrome.storage.sync.get(['key', 'lvnr'], function(result) {
var formData = {
"priv_key": result.key,
"lv_number": result.lvnr
};
postData(JSON.stringify(formData));
});
async function postData(formData) {
const response = await fetch("http://localhost/learneasy_js/lCheck3.php", {
method: 'POST',
mode: "cors",
credentials: "same-origin",
headers: {
'Content-Type': 'application/json'
},
referrer: 'no-referrer',
body: formData
});
const json = await response.json();
setInfo(json);
}
}

Javascript Fetch Body JSON List

I am trying to make a post request and getting this exception:
"unsupported BodyInit type"
I think the issue is with the body of the request. phoneNumbers takes on the form phoneNumbers = ["1234567890", "1234567891"] (i.e. a list of strings). I tried to do JSON.stringify(phoneNumbers) as the body, but that seems to return "[]", even if the list is not empty.
export async function findUsersByPhoneNumbersNotFollowing(userId, phoneNumbers) {
const reqConfig = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: phoneNumbers,
};
const response = await authfetch(`${API_URL}/following/recommendations/${userId}`, reqConfig);
if (response.error) {
throw new Error(response.error);
}
return response;
}
Where am I going wrong? The API endpoint is expecting List<String> (using spring framework, and the controller method takes this param in annotated #RequestBody)
Try sending a JSON Object instead a plain array:
const reqConfig = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({
paramName: phoneNumbers
}),
};
Replace paramName for the name you are expecting on your API endpoint.

How can I add raw data body to an axios request?

I am trying to communicate with an API from my React application using Axios. I managed to get the GET request working, but now I need a POST one.
I need the body to be raw text, as I will write an MDX query in it. Here is the part where I make the request:
axios.post(baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
{
headers: { 'Authorization': 'Basic xxxxxxxxxxxxxxxxxxx',
'Content-Type' : 'text/plain' }
}).then((response) => {
this.setState({data:response.data});
console.log(this.state.data);
});
Here I added the content type part. But how can I add the body part?
Thank you.
Edit:
Here is a screenshot of the working Postman request
How about using direct axios API?
axios({
method: 'post',
url: baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
headers: {},
data: {
foo: 'bar', // This is the body part
}
});
Source: axios api
You can use postman to generate code. Look at this image. Follow step1 and step 2.
If your endpoint just accepts data that have been sent with Body (in postman), You should send FormData.
var formdata = new FormData();
//add three variable to form
formdata.append("imdbid", "1234");
formdata.append("token", "d48a3c54948b4c4edd9207151ff1c7a3");
formdata.append("rate", "4");
let res = await axios.post("/api/save_rate", formdata);
You can use the below for passing the raw text.
axios.post(
baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
body,
{
headers: {
'Authorization': 'Basic xxxxxxxxxxxxxxxxxxx',
'Content-Type' : 'text/plain'
}
}
).then(response => {
this.setState({data:response.data});
console.log(this.state.data);
});
Just have your raw text within body or pass it directly within quotes as 'raw text to be sent' in place of body.
The signature of the axios post is axios.post(url[, data[, config]]), so the data is where you pass your request body.
The key is to use "Content-Type": "text/plain" as mentioned by #MadhuBhat.
axios.post(path, code, { headers: { "Content-Type": "text/plain" } }).then(response => {
console.log(response);
});
A thing to note if you use .NET is that a raw string to a controller will return 415 Unsupported Media Type. To get around this you need to encapsulate the raw string in hyphens like this and send it as "Content-Type": "application/json":
axios.post(path, "\"" + code + "\"", { headers: { "Content-Type": "application/json" } }).then(response => {
console.log(response);
});
C# Controller:
[HttpPost]
public async Task<ActionResult<string>> Post([FromBody] string code)
{
return Ok(code);
}
https://weblog.west-wind.com/posts/2017/sep/14/accepting-raw-request-body-content-in-aspnet-core-api-controllers
You can also make a POST with query params if that helps:
.post(`/mails/users/sendVerificationMail`, null, { params: {
mail,
firstname
}})
.then(response => response.status)
.catch(err => console.warn(err));
This will POST an empty body with the two query params:
POST
http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName
Source: https://stackoverflow.com/a/53501339/3850405
Here is my solution:
axios({
method: "POST",
url: "https://URL.com/api/services/fetchQuizList",
headers: {
"x-access-key": data,
"x-access-token": token,
},
data: {
quiz_name: quizname,
},
})
.then(res => {
console.log("res", res.data.message);
})
.catch(err => {
console.log("error in request", err);
});
This should help
You can pass the params like so
await axios.post(URL, {
key:value //Second param will be your body
},
{
headers: {
Authorization: ``,
'Content-Type': 'application/json'
}
this makes it easier to test/mock in Jest as well
I got same problem. So I looked into the axios document.
I found it. you can do it like this. this is easiest way. and super simple.
https://www.npmjs.com/package/axios#using-applicationx-www-form-urlencoded-format
var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
You can use .then,.catch.
For sending form data in the body, you can just format the data in url params like this 'grant_type=client_credentials&client_id=12345&client_secret=678910' and attached it to data in the config for axios.
axios.request({
method: 'post',
url: 'http://www.example.com/',
data: 'grant_type=client_credentials&client_id=12345&client_secret=678910',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
})
The only solution I found that would work is the transformRequest property which allows you to override the extra data prep axios does before sending off the request.
axios.request({
method: 'post',
url: 'http://foo.bar/',
data: {},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
transformRequest: [(data, header) => {
data = 'grant_type=client_credentials'
return data
}]
})
This worked fine for me when trying to send authentication credential in body in raw json format.
let credentials = {
username: "your-username",
password: "your-password",
};
axios
.get(url, { data: credentials })
.then((res) => {
console.log(res.data);
})
Used in React js
let url = `${process.env.REACT_APP_API}/validuser`;
let body = JSON.stringify({
loginid: "admin",
password: "admin",
});
var authOptions = {
method: "post",
url: url,
data: body,
headers: {
"Content-Type": "application/json",
},
json: true,
};
axios(authOptions)
.then((resp) => {
console.log("response :- ",resp);
})
.catch((error) => {
alert(error);
});
axios({
method: 'post', //put
url: url,
headers: {'Authorization': 'Bearer'+token},
data: {
firstName: 'Keshav', // This is the body part
lastName: 'Gera'
}
});
There many methods to send raw data with a post request. I personally like this one.
const url = "your url"
const data = {key: value}
const headers = {
"Content-Type": "application/json"
}
axios.post(url, data, headers)
let url='<your domain.extension>';
let data= JSON.stringify('mydata');
axios
.get(url, { data })
.then((res) => {
console.log(res.data);
})
For me this solution works, i.e. JSON.stringify(your data) , just convert your raw data using JSON.stringify method.
I hope this works.

Fetch: POST JSON data

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'
}
});

Categories

Resources