How can I retrieve my post request using JavaScript - javascript

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

Related

DJango GET Request from database into JSON

I got a question with my Django project. I have a database and want to get data into JavaScript with a fetch request. The data should just be in JSON. This was my attempt with Serializer. Is there a more easy way, than writing a whole serializer.py. Does anybody have an idea what to do.
JavaScript:
fetch('', {
method: 'GET',
})
.then(response => response.json())
.then(data => {
console.log(data);
});
DJango views.py:
def ausgeben(request):
if request.method == 'GET':
ausgeben = Schraube.objects.all()
serializer = SchraubeSerializer(schrauben, many=True)
return JsonResponse(serializer.data, safe=False)
return render(request, 'AR-Ausgeben.html', all_items)

Accessing response in case of Error when using fetch API

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.

Send data to database via fetch and subsequently display this data to html page via fetch again without submitting form or refreshing the page

I have a django app. I'm typing a comment in a form and I'm sending it to my database via fetch.
my js code
document.getElementById("comment-form").onsubmit = function write_comment(e) {
e.preventDefault();
const sxolio = document.getElementsByName("say")[0].value;
fetch('/comment', {
method: 'POST',
body: JSON.stringify({
say: sxolio
})
})
.then(response => response.json())
.then(result => {
//print result
console.log(result);
});
my views.py
#requires_csrf_token
#login_required(login_url = 'login')#redirect when user is not logged in
def comment(request):
if request.method != 'POST':
return JsonResponse({"error": "POST request required."}, status=400)
new_comment = json.loads(request.body)
say = new_comment.get("say", "")
user = request.user
comment = Comment(
user = user,
say = say,
photo = Userimg.objects.get(user = user).image
)
comment.save()
return JsonResponse({"message": "Comment posted."}, status=201)
Next thing i wanna do is to display this comment and all the other data from my db, to my html page without refreshing.The moment i push the post button i want the comment to be dispayed. I dont want to update the page with some element.innerHTML = data.
my js code
function display_comments() {
fetch('/all_comments')
.then(response => response.json())
.then(all_comments => {
do some stuff
my views.py
#login_required(login_url = 'login')#redirect when user is not logged in
def all_comments(request):
all_comments = Comment.objects.order_by("-date").all()
print(all_comments[0].serialize())
return JsonResponse([comment.serialize() for comment in all_comments], safe=False)
If i use preventDefault i can see that my db is been updated but i can't retrieve the data.
If i skip prevent default everything works fine but my page is refreshing simultaneously.
Is there any way to do them both without refreshing the page?
The most likely problem is that your all_comments view request is being made before the comment has finished saving to the DB.
It is important that the response for comment is completely returned before the fetch to all_comments is started. You can accomplish this by doing the following...
function display_comments() {
fetch('/all_comments')
.then(response => response.json())
.then(all_comments => {
console.log(all_comments);
});
}
document.getElementById("comment-form").onsubmit = function write_comment(e) {
e.preventDefault();
const sxolio = document.getElementsByName("say")[0].value;
fetch('/comment', {
method: 'POST',
body: JSON.stringify({
say: sxolio
})
})
.then(response => response.json())
.then(result => {
// print result
console.log(result);
// The request to /comment has finished it is now safe to request all
// comments.
display_comments();
});
}

How to return error from Flask so JavaScript catches it

I have an application running a Flask backend with a React frontend and I'm trying to do some error handling for the front end and display the error message to the user. Here is a simplified version of my files:
Flask
#app.route('/api/download', methods=['POST'])
def download():
data = request.json
#Get data from external API via a post request here
try:
req = urllib.request.Request(url, data, headers)
with urllib.request.urlopen(req) as f:
res = f.read()
print("Success")
data = json.loads(res.decode())
df = pd.json_normalize(data['observationList'])
#Do some pandas magic here
retData = df.to_json(orient="records")
return retData
except Exception as e:
pprint(e)
return jsonify(message='password_update_error'),500
JavaScript
fetch("/api/download", {
method:"POST",
cache: "no-cache",
headers:{
'Content-Type': 'application/json'
},
body: JSON.stringify({
values: this.state.values
})
}).then((response) => response.json())
.then(data => {
this.setState({ sdata: data }, () => {
// click the CSVLink component to trigger the CSV download
setTimeout(() => {
this.csvLink.current.link.click();
});
})
}).catch(err => {
errorBox.innerHTML = "<span style='color: red;'>"+
"Could not get data.</span>"
})
This currently gives me two errors:
TypeError: Data should be a "String", "Array of arrays" OR "Array of objects"
TypeError: Cannot read property 'link' of null
I understand what the problem is but I don't know how to return errors so javascript catches it and then displays it in the box like I want it to. Any ideas? Thank you!
At first glance, why don't you just return the error code? It should solve the errors you're getting.
#app.route('/api/download', methods=['POST'])
def download():
data = request.json
#Get data from external API via a post request here
try:
req = urllib.request.Request(url, data, headers)
with urllib.request.urlopen(req) as f:
res = f.read()
print("Success")
data = json.loads(res.decode())
df = pd.json_normalize(data['observationList'])
#Do some pandas magic here
retData = df.to_json(orient="records")
return retData
except Exception as e:
pprint(e)
return 500

Why doesn't the csrf_exempt work on my view in Django?

I am making a fetch request to one of the Urls as:
function like(id){
fetch(`/likepost/${id}`, {
method:'PUT',
body: JSON.stringify({
'id':id
})
})
.then(response => response.json())
.then(result => {
console.log(result)
})
and the url maps to this view:
path('likepost/<int:post_id>', views.likepost,name='like')
and the view is defined as:
#csrf_exempt
def likepost(request, post_id):
if request.method == 'PUT':
data = json.loads(request.body)
id = data.get('id')
post = Post.objects.get(pk=id)
post.likes = post.likes+1
post.save()
return JsonResponse({'message':'liked succcessfuly'})
else:
return JsonResponse({'Message':'request should be post'})
but I am getting this error:
Forbidden (CSRF token missing or incorrect.): /likepost/12
even though I have used csrf_exempt, can anyone help me?

Categories

Resources