html-javascript
var csrftoken = $('[name="csrfmiddlewaretoken"]').val();
$('#Save').click(function () {
var ajaxdata = {
exam: $('#Exam').val()
};
$.ajax({
url: '/save',
type: 'POST',
dataType: 'json',
data: JSON.stringify(ajaxdata),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
"X-CSRFToken": csrftoken
},
credentials: 'include',
success: function () {
alert(ajaxdata);
console.log(ajaxdata);
},
error:function (xhr, ajaxOptions, thrownError){
console.log(ajaxdata);
}
});
}
views.py
import json
from django.http import HttpResponse
def save(request=request):
data = json.loads(request.body)
testexam = data['exam']
testexam = request.POST.get('exam')
testobj = MyObject.objects.filter(name="David").first()
testobj.Exam = testexam
testobj.save()
return HttpResponse(json.dumps({"success": True}), content_type="application/json")
These are my html and views now.
Removed the "flask" part.
data = json.loads(request.body)
allowed me to receive data successfully!
Still don't quite understand why " request.POST " didn't work.
I'll come back later to update if I manage to know the reason!
Thanks for the comments and useful suggestions!
No need using the flask.
This is how I receive the data:
data = json.loads(request.body)
and it all works well!
Thanks for all the comments, suggestions, answers! Really appreciated!
your ajax code is just fine, however you're doing few things wrong. First of all, in your html part.
<h1> This is simple html</h1>
<input type="text" id = "Exam">
<button type="button" id="Save">Save</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var csrftoken = $('[name="csrfmiddlewaretoken"]').val();
$('#Save').click(function () {
var ajaxdata = {
exam: $('#Exam').val()
};
$.ajax({
url: '/save',
type: 'POST',
dataType: 'json',
data: JSON.stringify(ajaxdata),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
"X-CSRFToken": csrftoken
},
credentials: 'include',
success: function () {
alert(ajaxdata)
},
error:function (xhr, ajaxOptions, thrownError){
console.log("this is an error")
}
});
});
</script>
You were initiating the ajaxdata before the click event happened, which may lead to the null value of #Exam filed.
Now getting back to your Flask part, you can't do request.POST with the data sent through Ajax request. Rather you can access all the data you sent through your js with request.data, below is the code which is working successfully.
from flask import Flask, request,send_from_directory
import json
# set the project root directory as the static folder, you can set others.
app = Flask(__name__)
#app.route('/home')
def root():
#return "this is home"
return send_from_directory("/home/ekbana/Documents/","index.html")
#app.route('/save',methods=['POST'])
def save(request=request):
print(request.data.decode("utf-8")) #We need to decode because it's a byte
#not a string
data = json.loads(request.data.decode("utf-8"))
#data here is {'exam': 'a text'} a dict in this case
testexam = data["exam"]
testobj = MyObject.objects.filter(name="David").first()
testobj.Exam = testexam
testobj.save()
return HttpResponse(json.dumps({"success": True}), content_type="application/json")
This is working fine with me, I replicated a simple example for your requirement. Aslo make sure to use methods=["POST"] if you want your route to recieve the POST request, if you didn't specify it, it may lead to HTTP_405_METHOD_NOT_ALLOWED.
Related
I have attempted to create a request in javascript, that has previously worked using python just fine.
the following is an accurate representation of the code I used to post the request with python:
url = 'https://website.com/api/e1'
header = {
'authorization': 'abcd1234'
}
payload = {
'content': "text",
}
r = requests.post(url, data=payload,headers=header )
This (above) works just fine in python.
now what I did in javascript is the following:
payload = {
"content": "this is text",
};
fetch("https://website.com/api/e1", {
method: "POST",
headers: {
"authorization":
"abcd1234",
},
body: JSON.stringify(payload),
});
but this is returning the error
400- Bad request
When using data parameters on python requests.post, the default Content-Type is application/x-www-form-urlencoded(I couldn't find it on the document, but I checked the request. If you know, please leave a comment).
To achieve the same result with fetch, you must do as follows.
const payload = {
'content': 'this is text',
};
fetch('https://website.com/api/e1', {
method: 'POST',
headers: {
'authorization': 'abcd1234',
},
body: new URLSearchParams(payload),
});
You don't need to do this body: JSON.stringify(payload), rather you can simply pass payload in body like this body:payload
I'm trying to send form data from a NativeScript app to a TYPO3-Webservice.
This is the JavaScript I'm using:
httpModule.request({
url: "https://my.domain.tld/webservice?action=login",
method: "POST",
headers: { "Content-Type": "application/json" },
content: JSON.stringify({
username:username,
password:password
})
}).then((response) => {
console.log("got response");
console.log(response.content);
//result = response.content.toJSON();
callback(response.content.toJSON());
}, (e) => {
console.log("error");
console.log(e);
});
But I can't read this data in the controller. Even with this:
$rest_json = file_get_contents("php://input");
$postvars = json_decode($rest_json, true);
$postvars is empty. $_POST is empty, too (which is - according to some docs - because the data is sent as JSON and thus the $_POST-Array isn't populated.
Whatever I do, whatever I try, I can't get those variables into my controller.
I tried it with fetch as well as with formData instead of JSON.stringify, same result.
I might have to add, that when I add the PHP-part in the index.php of TYPO3, $postvars is being populated. So I guess something goes missing, until the controller is called.
Any ideas?
the nativescript part seems ok, your problem must be corrected in the server side.
i use similare call and its works
// send POST request
httpModule.request({
method: "POST",
url: appSettings.getString("SERVER") + '/product/list',
content: JSON.stringify(data),
headers: {"Content-Type": "application/json"},
timeout: 5000,
}).then(response => { // handle replay
const responseAsJson = response.content.toJSON();
console.log('dispatchAsync\n\tresponse:', responseAsJson);
}, reason => {
console.error(`[ERROR] httpModule, msg: ${reason.message}`);
});
https://github.com/simpleblog-project/Simple-Blog/issues/1
$.ajax({
method: "POST",
url: "http://localhost:5000/auth/login",
data: JSON.stringify({
"name" : id,
"password" : password
}),
contentType: 'application/json'
})
.done(function(msg) {
if (msg.access_token) {
createCookie(msg.access_token);
window.location.href = './Main.html';
}
else {
if(msg.message)
{
console.log(msg.message);
alert(msg.message);
}
}
});
this
else{
if(msg.message)
{
console.log(msg.message);
alert(msg.message);
}
}
that is not working.
log was jquery-3.3.1.min.js:2 POST http://localhost:5000/auth/login 400 (BAD REQUEST)
this problem is related by app.py this part ▼
#app.route('/auth/login', methods=['POST'])
def login():
data = request.json
name = data['name']
password = data['password']
user = User.query.filter_by(name=name).first()
if user is None or not User.verify_password(user, password):
return {"message": "invalid username or password"}, 400
return {
'access_token': create_access_token(user.id, expires_delta=access_token_exdelta),
'refresh_token': create_refresh_token(user.id, expires_delta=refresh_otken_exdelta)
}
Open the browser to your page and put a breakpoint in the browser on the code, you can click on F12 to open the developer window click on console and navigate to the line. click on the line to add a breakpoint.(red bullet) For ex.
The if statement would be a nice spot to put a breakpoint on. (javascript side) when in a breakpoint ( you see a blue line / redline) hovering on that spot when you hit it, and you can see which variables you have. and in console you can type "msg" and it would show you the current state of the msg object.
also might want to add a error part to the ajax call, just to check if the ajax call itself went ok.
$.ajax({
method: "POST",
url: "http://localhost:5000/auth/login",
data: JSON.stringify({
"name" : id,
"password" : password
}),
contentType: 'application/json',
success: function (data, status, xhr) {
console.log("Succes!" + data);
},
error: function (xhr) {
console.log("Error happened" +xhr.status);
}
});
Look at the documentation how the ajax call works:
https://api.jquery.com/jQuery.ajax/
and check if you get the object "msg" back from the server.
Good luck :).
I wrote a rest webservice and to avoid the error I got in my java code which is:
The registered message body readers compatible with the MIME media type, I have to add to my $http.post a 'Content-Type': 'application/x-www-form-urlencoded' or 'Content-Type': 'application/json'.
I am using Angularjs 1.3.5 and whenever I tried to add the headers {content-type.... }, I failed. What can I do exactly to solve my problem?
$scope.save = function(url,data) {
var data_stack = $scope.stack;
$http.post(url, data_stack)
.then(
function(response){
},
function(response){
});
}
<form ng-submit="save()">
<input ng-model="stack"></input>
<button type="submit">Save</button>
</form>
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type':'application/x-www-form-urlencoded'
// or 'Content-Type':'application/json'
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
I wrote a JQuery script to do a user login POST (tried to do what I have done with C# in the additional information section, see below).
After firing a POST with the JQuery code from my html page, I found the following problems:
1 - I debugged into the server side code, and I know that the POST is received by the server (in ValidateClientAuthentication() function, but not in GrantResourceOwnerCredentials() function).
2 - Also, on the server side, I could not find any sign of the username and password, that should have been posted with postdata. Whereas, with the user-side C# code, when I debugged into the server-side C# code, I could see those values in the context variable. I think, this is the whole source of problems.
3 - The JQuery code calls function getFail().
? - I would like to know, what is this JQuery code doing differently than the C# user side code below, and how do I fix it, so they do the same job?
(My guess: is that JSON.stringify and FormURLEncodedContent do something different)
JQuery/Javascript code:
function logIn() {
var postdata = JSON.stringify(
{
"username": document.getElementById("username").value,
"password": document.getElementById("password").value
});
try {
jQuery.ajax({
type: "POST",
url: "http://localhost:8080/Token",
cache: false,
data: postdata,
dataType: "json",
success: getSuccess,
error: getFail
});
} catch (e) {
alert('Error in logIn');
alert(e);
}
function getSuccess(data, textStatus, jqXHR) {
alert('getSuccess in logIn');
alert(data.Response);
};
function getFail(jqXHR, textStatus, errorThrown) {
alert('getFail in logIn');
alert(jqXHR.status); // prints 0
alert(textStatus); // prints error
alert(errorThrown); // prints empty
};
};
Server-side handling POST (C#):
public override async Task ValidateClientAuthentication(
OAuthValidateClientAuthenticationContext context)
{
// after this line, GrantResourceOwnerCredentials should be called, but it is not.
await Task.FromResult(context.Validated());
}
public override async Task GrantResourceOwnerCredentials(
OAuthGrantResourceOwnerCredentialsContext context)
{
var manager = context.OwinContext.GetUserManager<ApplicationUserManager>();
var user = await manager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError(
"invalid_grant", "The user name or password is incorrect.");
context.Rejected();
return;
}
// Add claims associated with this user to the ClaimsIdentity object:
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
foreach (var userClaim in user.Claims)
{
identity.AddClaim(new Claim(userClaim.ClaimType, userClaim.ClaimValue));
}
context.Validated(identity);
}
Additional information: In a C# client-side test application for my C# Owin web server, I have the following code to do the POST (works correctly):
User-side POST (C#):
//...
HttpResponseMessage response;
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>( "grant_type", "password"),
new KeyValuePair<string, string>( "username", userName ),
new KeyValuePair<string, string> ( "password", password )
};
var content = new FormUrlEncodedContent(pairs);
using (var client = new HttpClient())
{
var tokenEndpoint = new Uri(new Uri(_hostUri), "Token"); //_hostUri = http://localhost:8080/Token
response = await client.PostAsync(tokenEndpoint, content);
}
//...
Unfortunately, dataType controls what jQuery expects the returned data to be, not what data is. To set the content type of the request data (data), you use contentType: "json" instead. (More in the documentation.)
var postdata = JSON.stringify(
{
"username": document.getElementById("username").value,
"password": document.getElementById("password").value
});
jQuery.ajax({
type: "POST",
url: "http://localhost:8080/Token",
cache: false,
data: postdata,
dataType: "json",
contentType: "json", // <=== Added
success: getSuccess,
error: getFail
});
If you weren't trying to send JSON, but instead wanted to send the usual URI-encoded form data, you wouldn't use JSON.stringify at all and would just give the object to jQuery's ajax directly; jQuery will then create the URI-encoded form.
try {
jQuery.ajax({
type: "POST",
url: "http://localhost:8080/Token",
cache: false,
data: {
"username": document.getElementById("username").value,
"password": document.getElementById("password").value
},
dataType: "json",
success: getSuccess,
error: getFail
});
// ...
To add to T.J.'s answer just a bit, another reason that sending JSON to the /token endpoint didn't work is simply that it does not support JSON.
Even if you set $.ajax's contentType option to application/json, like you would to send JSON data to MVC or Web API, /token won't accept that payload. It only supports form URLencoded pairs (e.g. username=dave&password=hunter2). $.ajax does that encoding for you automatically if you pass an object to its data option, like your postdata variable if it hadn't been JSON stringified.
Also, you must remember to include the grant_type=password parameter along with your request (as your PostAsync() code does). The /token endpoint will respond with an "invalid grant type" error otherwise, even if the username and password are actually correct.
You should use jquery's $.param to urlencode the data when sending the form data . AngularJs' $http method currently does not do this.
Like
var loginData = {
grant_type: 'password',
username: $scope.loginForm.email,
password: $scope.loginForm.password
};
$auth.submitLogin($.param(loginData))
.then(function (resp) {
alert("Login Success"); // handle success response
})
.catch(function (resp) {
alert("Login Failed"); // handle error response
});
Since angularjs 1.4 this is pretty trivial with the $httpParamSerializerJQLike:
.controller('myCtrl', function($http, $httpParamSerializerJQLike) {
$http({
method: 'POST',
url: baseUrl,
data: $httpParamSerializerJQLike({
"user":{
"email":"wahxxx#gmail.com",
"password":"123456"
}
}),
headers:
'Content-Type': 'application/x-www-form-urlencoded'
})
})