I need to convert this to ajax.
curl -X POST \
-H "X-Parse-Application-Id: ****************" \
-H "X-Parse-REST-API-Key: ******************" \
-H "Content-Type: application/json" \
-d '{
"deviceType": "ios",
"deviceToken": "result" ,
"channels": [
""
]
}' \
https://api.parse.com/1/installations
I found the solution is to create an ajax post method. So in this example, you would do the following ajax method.
var headers = {
"X-Parse-Application-Id":"Your ID",
"X-Parse-REST-API-Key":"Your Rest API Key"
};
// Convert data object to JSON string:
var userData = { "deviceType": "the device or the variable that says the device",
"deviceToken": "The Token itself or the variable with the token",
"channels": [""]
};
var data = JSON.stringify(userData);
$.ajax({
headers: headers,
type: 'POST',
url: "https://api.parse.com/1/installations",
contentType: "application/json",
data: data,
dataType:"json",
success:function(data) {
// We log the responce from the server just to check.
alert("data:" + JSON.stringify(data) + " status: " + status);
},
error:function(data) {
// Show error message:
alert("Your data didn't save!" + JSON.stringify(data));
}
});
Related
I consistently receive the response of 'operation not found' when I send a GraphQL query or mutation in Cypress. Taking tips from this post https://stackoverflow.com/a/68750026/16958500 I have the following in my it block (its working in Postman)
it('Retrieve and Store Session Token', () => {
const query = `mutation {
requestSMSSessionToken(phoneNumber: "1666555021"){
cookieKey
tokenValue
expires
}
}`;
cy.request({
method: 'POST',
url: '/',
headers: {
'Content-Type': 'application/json',
},
body: { query },
}).then((res)=>{
cy.log(JSON.stringify(res))
expect(res.status).to.eq(200)
});
})
Here is my Postman Curl Code Snippet (that's working)
curl --location --request POST '/' \
--header 'Content-Type: application/json' \
--data-raw '{"query":"mutation {\r\n requestSMSSessionToken(phoneNumber: \"1666555021\"){\r\n \r\n cookieKey\r\n tokenValue\r\n expires\r\n \r\n }\r\n }","variables":{}}'
any tips to share to get this working?
I want conver to ajax to curl.
curl localhost:8080/oauth/token -h foo:bar -d grant_type=password -d username=test#gmail.com -d password=1
The above command succeeds.
but ajax fail...
$.ajax({
url: 'http://localhost:8080/oauth/token',
type: 'POST',
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Basic' + btoa('foo:bar'));
},
data: {
grant_type: 'password',
username: 'test#gmail.com',
password: '1'
},
complete: function(result) {
console.log('complete', result);
},
success: function(result) {
console.log('success', result);
},
error: function(result) {
console.log('error', result);
}
});
I converted to ajax and the following error appears.
Response for preflight has invalid HTTP status code 401
responseJSON : undefined
What is the problem?
I found solution.
Modify OauthServer
Change "source.registerCorsConfiguration("/**", configAutenticacao);" to "source.registerCorsConfiguration("/oauth/token", configAutenticacao);" in corsFilterRegistrationBean
My API responds to the following curl request:
curl --data "session[email]=email#gmail.com&session[password]=password" -H 'Accept: application/vnd.my-app.v1' \http://my-app.dev/sessions
But not to this Ajax:
$.ajax({
url: '/sessions',
method: 'POST',
headers: 'Accept: application/vnd.superstar-is-back.v1',
data: {
session: {
email: this.email,
password: this.password,
},
}
})
Am I getting something wrong with this syntax?
I'm not sure how this impacts Rails Routing, but based on the jQuery docs, I think the headers property needs to be an object: headers: { Accept: 'application/vnd.superstar-is-back.v1' }
I use Haskell with servant-0.7.1 fo realisation server.Below is my source code:
type UserRestAPI
= "rest" :> "users" :> Get '[JSON] [User]
:<|> "rest" :> "user" :> ReqBody '[JSON] User :> Post '[PlainText] Text
serverUserRestAPI :: ServerT UserRestAPI AppM
serverUserRestAPI = usersGet :<|> userPost
userPost :: User -> AppM Text
userPost user = do
newUser <- runDb $ do insert user
liftIO $ putStrLn $ show newUser
return $ append (toPathPiece newUser) "\r\n"
The model of User:
let mongoSettings = (mkPersistSettings (ConT ''MongoContext)) {mpsGeneric = False}
in share [mkPersist mongoSettings, mkMigrate "migrateAll"] [persistLowerCase|
User
fam String
im String
ot String
email String
login String
pswd String
deriving Show
|]
$(deriveJSON defaultOptions ''User)
For testin curl was used, as shown below.
curl --verbose --request POST --header "Content-Type: application/json" \
--data '{"userFam": "Fam", "userIm": "Im", "userOt": "Ot", "userEmail": "mail#mail.ru", "userLogin": "test", "userPswd": "test"}' \
http://127.0.0.1:3000/rest/user
Everything is working. The data added to the database.But when I use ajax from backend, as shown below.
var formElement = $("#id_form");
var formData = formElement.serializeArray();
var objectData = {};
for(var i = 0; i < formData.length; i++)
objectData[formData[i].name] = formData[i].value;
$.ajax({
type: "POST",
async: true,
url: "/rest/user",
dataType: "text",
cache : false,
contentType : "application/json",
data: objectData,
success: function(result){
consoloe.log(result)
},
error: function(jqXHR, status, err) {
console.log(err)
}
});
I get an error!
jquery.js:4 POST http://127.0.0.1:3000/rest/user 400 (Bad Request)
The debugger checked object objectData. All right (Object {userFam: "qqq", userIm: "www", userOt: "eee", userEmail: "rrr", userLogin: "ttt"…}).
I can not understand what was going on.
it's really a problem with your ajax call as you don't provide a valid JSON object but just objectData.toString() as data: - the common solution is to use JSON.stringify:
$.ajax({
type: "POST",
async: true,
url: "/rest/user",
dataType: "json",
cache : false,
data: JSON.stringify(objectData),
success: function(result){
// ...
},
error: function(jqXHR, status, err) {
console.log(err)
}
});
another great example what is wrong with untyped languages ;)
i'm using play framework 2.0.4
i have a route :
POST /addMail controllers.Application.addMail()
In my controller Application i define the addMail method :
public static Result addMail()
{
JsonNode json = request().body().asJson();
Long id = json.findPath("id").asLong(0);
String email = json.findPath("email").getTextValue();
GameScore gs = GameScore.findById(id);
gs.setEmail(email);
gs.save();
return ok();
}
If i call this method through CURL i have no problem :
curl --header "Content-type: application/json" --request POST --data '{"id": 13, "email": "test#DB.com"}' http://localhost:9000/addMail
But if i call this method through an AJX request i have a 500 response.
$addMailBtn.click(function(event) {
$this = $(this);
var id = $this.attr("id").substring(14);
var email = $("#saisieMailField_" + id).val();
$.ajax({
type: 'POST',
url: "#routes.Application.addMail()",
dataType:"json",
data: {"id":id, "email": '"' + email + '"'},
success: location.reload()
})
} );
If i print in my console my json data, json data is null when i perform my ajax request but is alright through curl.
I have tried to add
#BodyParser.Of(play.mvc.BodyParser.Json.class)
on my method but it doesn't change anything.
Thanks for your time.
This works for me. Note that i stringify the JSON object, and I think this is your problem.
$.ajax({
type: "POST",
url: "http://myservice:9000/api/v1/positions",
data: JSON.stringify({"nwLng":72.22,"nwLat":22.22, "seLng":22.22,"seLat":55.33}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) { alert(data); },
failure: function (errMsg) { alert(errMsg); }
});