I am using following fetchProtectedResource call to a REST Service:
return this.fetcher.fetchProtectedResource(url, {
method: 'PUT',
body: body
}, config)
.toPromise()
.then(response => response.json()
)
.catch(e => {
//How to get json from e object????
return null;
});
I can see in Browser that in case of error, the server return json in response but I cant find any documentation about the structure of this error Object to get this JSON.
Related
I have two projects, the first one is Node.JS.
jsonobj = JSON.stringify(generateMockData)
xhrToSoftware.send(jsonobj);
xhrToAPI.open("POST", "http://127.0.0.1:8000/path/", true);
xhrToAPI.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhrToAPI.send(jsonobj);
It's sending data to the second project Django Python. I can receive the data using my views.py.
post_data = json.loads(request.body.decode("utf-8"))
value = post_data.get('data')
print(value)
But I want to directly get the data from Node.JS to my Django Templates (javascript or jquery) is that possible?
for example:
<script>
//get the data that posted by the node.js
</script>
UPDATE:
I tried using the answers below like this one:
fetch('http://127.0.0.1:8000/path/')
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => console.error(error));
but I'm having an error it says that:
SyntaxError: Unexpected token '<', "<!--
<d"... is not valid JSON
I think that's because I'm returning an html file in my views.py:
def data(request):
if request.method == 'POST':
post_data = json.loads(request.body.decode("utf-8")) # for simulation
value = post_data.get('data')
return render(request, 'waterplant/iot/data.html')
so, I change it to jsonresponse like this:
def data(request):
if request.method == 'POST':
post_data = json.loads(request.body.decode("utf-8")) # for simulation
value = post_data.get('data')
return JsonResponse({"msg": value}, status=200)
After that I'm having an error ValueError: The view views.data didn't return an HttpResponse object. It returned None instead. I think that's because the value is empty yet. How can I prevent that? If I send a data using my Node.JS I want to return it as return JsonResponse({"msg": value}, status=200) Or you have any idea that I can access the data directly in my Django Python templates <script> here </script>
Basic js fetch()
If you use method "GET":
fetch('http://127.0.0.1:8000/path')
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => console.error(error));
If you use method "POST":
fetch(`http://127.0.0.1:8000/path`, {
method: "POST",
headers: {"Content-type": "application/json; charset=UTF-8"},
body: data
})
.then(response => response.json())
.then(json => {
console.log(json);
})
.catch(error => console.error('Error on fetch() call:\n', error));
Hope it could be useful!
If a get request is to be made from your webpage use fetch()
fetch('http://127.0.0.1:8000/path')
.then((response) => response.json())
.then((data) => console.log(data));
I have a JSON file I want to read from and write to that looks like this:
[
"test#example.com"
]
I want to add info to this file using the fetch() API. So far, I can only read from this file.
let handle = JSON.stringify(`test#example2.com`); // handle is fine irrelevant of "" or ``
const url = `../json/emails.json`; // URL is fine
const options = {
method: `POST`, // PUT return error at second fetch: SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data"
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: handle
};
fetch(url) // this fetch is fine
.then(response => {
if (!response.ok) {
throw new Error(`Error getting the stuff`);
}
return response;
})
.then(r => r.json())
.then(data => {
console.log(`Data: ` + data);
});
fetch(url, options)
.then(response => {
if (!response.ok) {
throw new Error(`Error getting the stuff`);
}
return response;
})
.then(a => a.json())
.then(append => {
console.log(`Data updated: ` + append);
}).catch(err => {
console.error('Request failed: ', err);
});
I get no errors (aside from that PUT comment); ESLint and TSLint don't have any problem with the JS file nor with the JSON file. What am I doing wrong?
fetch() is an API for making HTTP requests.
It can't write to files. In particular, nothing can write to arbitrary URLs. (Imagine if it was possible for any browser to write new data to http://www.google.com/!)
If you want your PUT or POST request to change data on your server, then you must write server-side code to process the request and edit the file.
I am having an issue in using the fetch method in the componentDidMount method when an api call is redirecting and returning the response. Initial 302 response is trying to get processed in then method after fetch and throwing a JSON.parse: unexpected end of data at line 1 column 1 of the JSON data. Any suggestion on how I can solve this issue ?
componentDidMount(){
let config = {
method: 'GET',
mode: 'no-cors',
redirect:'follow',
cache: 'default',
headers: new Headers({
'Content-Type': 'application/json'
})
};
fetch("ACTUAL_URL",config)
.then(response => response.text())
.then( val => JSON.parse(val))
.then(response => {
this.setState({val:response.json()})
})
}
API CALL response
-302
- 200
fetch only rejects in case of network error . For other cases you have to use
the ok method
fetch("ACTUAL_URL",config)
.then(function(data){
if (!data.ok) {
throw Error(data);
}
}).then(response => response.text())
.then( val => JSON.parse(val))
.then(response => {
this.setState({val:response.json()})
}).catch(function(error){
// handle the 302 error here
})
So i am trying to make this post request, following aurelia docs:
http://aurelia.io/hub.html#/doc/article/aurelia/fetch-client/latest/http-services/3
And this is the request:
httpClient.configure(config => {
config
.withBaseUrl(baseUrl)
});
this.client = httpClient;
this.client.fetch(`/api/Register/${userName}`, {
method: "post",
body: json(loginInformation),
headers: {
'Access-Control-Allow-Origin' : '*',
'Accept': 'application/json'
}
}) .then(response => this.safelyParseJSON(response))
.then(data => this.setup(data));
where safetyParseJSON is:
safelyParseJSON(response) {
var parsed
try {
parsed = response.json();
} catch (e) {
}
return parsed
}
but i keep receiving this error:
"uncaught (in promise) SyntaxError: Unexpected end of JSON input"
Anyone have any idea on what am i doing wrong?
Note:
I am receiving this error only when receiving 404 / 500 from the server, if the results are ok, this works.
Note2: that i am wrapping this function inside try-catch but this still doesn't work, it doesn't catch the exception.
Note3: I have tried to replace this line:
parsed = response.json();
with this line:
parsed = JSON.parse(response);
But than the response is always undefined.
check the response's status prior to calling .json():
.then(response => {
if (response.ok) {
return response.json().then(data => this.setup(data));
}
return Promise.reject(response.text());
});
I ended up using Jeremy Danyow answer, with a small change:
.then(response => {
if (response.ok && response.status === 200) {
return response.json().then(data => this.setup(data));
}
return Promise.reject(response.text());
});
adding the response.status check was necessary in my case as response.ok was true for status code 204 (No content) aswell.
I'm trying to do a POST request for authentication in Redux and I'm passing email & password as the body but it returns this error in the console:
Uncaught (in promise) SyntaxError: Unexpected end of input
I looked around for the answer and many people suggested that it might be a missing } brace but I looked for it and I don't think it's that.
Here is my fetch function.
export function loginUser(creds) {
let config = {
mode: 'no-cors',
method: 'POST',
headers: { 'Content-Type':'application/x-www-form-urlencoded' },
body: `email=${creds.email}&password=${creds.password}`
};
return dispatch => {
dispatch(requestLogin(creds));
return fetch('http://localhost:4000/api/authenticate', config)
.then(response =>
response.json()
.then(user => ({ user, response }))
).then(({ user, response }) => {
if (!response.ok) {
dispatch(loginError(user.message));
return Promise.reject(user);
} else {
localStorage.setItem('id_token', user.token);
dispatch(receiveLogin(user));
}
});
};
}
The fetch POST method calls the API and I see it in the networking tab and I see the response too but the fetch request stops at .then(response => after the url and config.
It's been two days and still can't find the solution. By the way, this works fine in Postman(chrome extension), so nothing wrong with the API.
Thanks
Answer EDIT: The issue was related to CORS, so for anyone having the same issue as I did.
I solve the same question when I remove
mode: 'no-cors'
from the config.
Anyway you could simplify your snippet code to:
fetch('http://localhost:4000/api/authenticate', config)
.then(response => response.json())
.then(({ user, response }) => {
And you should might add catch method to handle an Error object.