React-native axios method POST response.data null - post

I use React-native for my school project and axios to take data.
here is my function :
login(username, password){
axios({
method : 'post',
url : 'http://xxxx.xxxx.com/UserRestController.php',
data : {
accountId : 2
}
})
.then(function (response) {
console.log('data', response.data);
})
.catch(function (error) {
console.log(error);
});
}
when I try to show response, this is always null.
Like this
data Object {
"config": Object {
"adapter": [Function xhrAdapter],
"data": "{\"accountId\":2}",
"headers": Object {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json;charset=utf-8",
},
"maxContentLength": -1,
"method": "post",
"timeout": 0,
"transformRequest": Object {
"0": [Function transformRequest],
},
"transformResponse": Object {
"0": [Function transformResponse],
},
"url": "http://ariary.vola.mg/UserRestController.php",
"validateStatus": [Function validateStatus],
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
},
"data": "",
"headers": Object {
"access-control-allow-origin": "*",
"connection": "keep-alive",
"content-type": "text/html; charset=UTF-8",
"date": "Mon, 31 Jul 2017 13:29:28 GMT",
"server": "nginx",
"transfer-encoding": "chunked",
"vary": "Accept-Encoding",
"x-powered-by": "EasyEngine 3.7.4",
},
"request": XMLHttpRequest {
"DONE": 4,
"HEADERS_RECEIVED": 2,
I use axios.GET in another function, and it works great. Can someone help me?
Thanks

Try parsing the response to json before accessing it's data like this:
axios({
method : 'post',
url : 'http://xxxx.xxxx.com/UserRestController.php',
data : {
accountId : 2
}
})
.then((res) => res.json())
.then(function (response) {
console.log('data', response.data);
})
.catch(function (error) {
console.log(error);
});

After some test, my problem is not the response but my data. This is always null. the accountId is undefined in my server. But I don't know why?

Related

iOS: IncompleteSignatureException when calling AWS Amplify GET

I'm having an issue where I'm unable to do a GET Request to an AWS Amplify API even after seemingly configuring everything properly. Currently I'm using AWSMobileClient and the iOS Amplify SDK to develop an app:
AWSMobileClient.sharedInstance().getTokens { (tokens, err) in
NSLog("tokens: \(tokens.debugDescription)")
NSLog("tokens: \(tokens!.idToken!.claims.debugDescription)")
self.doInvokeAPI(token: tokens!.idToken!.tokenString!)
}
//...
func doInvokeAPI(token: String) {
let headerParameters = [
"Authorization" : token,
"Content-Type": "application/json",
"Accept": "application/json"
]
let queryParams = ["response" : "true"]
let request = RESTRequest(apiName: <ENDPOINT_NAME>, path: <PATH>, headers: headerParameters, queryParameters: queryParams, body: nil)
Amplify.API.get(request: request, listener: responseCallBack)
}
When I call Amplify.API.get(), I'm constantly getting a 403 Error, and after creating some helper functions (responseCallBack) to log the HTTP response, I'm receiving this, which shows it's an IncompleteSignatureException:
HTTP: <NSHTTPURLResponse: 0x283a580a0> { URL: <my-endpoint-url>/<my-path>?response=true } { Status Code: 403, Headers {
"Access-Control-Allow-Origin" = (
"*"
);
"Content-Length" = (
1158
);
"Content-Type" = (
"application/json"
);
Date = (
"Fri, 23 Oct 2020 21:22:06 GMT"
);
"access-control-allow-headers" = (
"*"
);
"x-amzn-errortype" = (
IncompleteSignatureException
);
"x-cache" = (
"Error from cloudfront"
);
} }
My amplifyconfiguration.json file looks like this:
{
"api": {
"plugins": {
"awsAPIPlugin": {
<MY_ENDPOINT_NAME>: {
"endpointType": "REST",
"endpoint": <MY_ENDPOINT_URL>,
"region": "us-west-2",
"authorizationType": "AMAZON_COGNITO_USER_POOLS"
},
<MY_OTHER_ENDPOINT_NAME>: {
"endpointType": "REST",
"endpoint": <MY_ENDPOINT_URL>,
"region": "us-west-2",
"authorizationType": "AMAZON_COGNITO_USER_POOLS"
}
}
},
},
"auth": {
"plugins": {
"awsCognitoAuthPlugin": {
"IdentityManager": {
"Default": {}
},
"CredentialsProvider": {
"CognitoIdentity": {
"Default": {
"PoolId": <IDENTITY_POOL_ID>,
"Region": "us-west-2"
}
}
},
"CognitoUserPool": {
"Default": {
"PoolId": <USER_POOL_ID>,
"AppClientId": <APP_CLIENT_ID>,
"Region": "us-west-2"
}
},
}
}
},
}
And my awsconfiguration.json looks like this:
{
"UserAgent": "aws-amplify/cli",
"Version": "1.0.5",
"IdentityManager": {
"Default": {}
},
"CredentialsProvider": {
"CognitoIdentity": {
"Default": {
"PoolId": <IDENTITY_USER_POOL_ID>,
"Region": "us-west-2"
}
}
},
"CognitoUserPool": {
"Default": {
"PoolId": <USER_POOL_ID>,
"AppClientId": <APP_CLIENT_ID>,
"Region": "us-west-2"
}
}
}
I can authenticate into my app (Auth.signIn() works) and Amplify.configure() in AppDelegate.swift doesn't seem to run into issues, since no errors occur when attempting to configure, so it looks like it passes that point. But when I try to call the API, I receive this error. I include the JWT token in the Authorization header when making the request, and have triple checked that I do not have typos. Does anyone have an idea as to why I cannot call the API?

Mountebank - How do I assert message body is JSON format in a POST request in mountebank

I want to stub and check the message body in POST request in mountebank,
{
"port": "22001",
"protocol": "http",
"name": "login_user",
"stubs": [
{
"responses": [
{
"is": {
"statusCode": 201,
"headers": {
"Content-Type": "application/json"
},
"body": {}
},
"_behaviors": {
"wait": 100
}
}
],
"predicates": [
{
"equals": {
"path": "/login_user",
"method": "POST",
"headers": {
"Content-Type": "application/json"
},
"body": {
"name": "Tony",
"age": "20"
}
}
}
]
}
]
}
if a message body in JSON format. expected response status Code 200.
for Example
{
"body": {
"name": "Tony",
"age": "20"
}
}
if a message body in JSON format but JSON string. expected response status Code 400.
for Example
{
"body": "{\"name\": \"Tony\", \"age\": \"20\"}"
}
You could achieve this with a 'matches' predicate containing a (pretty crude in this example) regex to capture any string input and return a 400:
"stubs": [
{
"responses": [
{
"is": {
"statusCode": 400,
"headers": {
"Content-Type": "application/json"
},
"body": {}
},
"_behaviors": {
"wait": 100
}
}
],
"predicates": [
{
"matches": {
"path": "/login_user",
"method": "POST",
"body": ".*\\\\\\\"name.*"
}
}
]
},
{
"responses": [
{
"is": {
"statusCode": 201,
"headers": {
"Content-Type": "application/json"
},
"body": {}
},
"_behaviors": {
"wait": 100
}
}
],
"predicates": [
{
"equals": {
"path": "/login_user",
"method": "POST",
"headers": {
"Content-Type": "application/json"
},
"body": {
"name": "Tony",
"age": "20"
}
}
}
]
}
]
Alternatively, you can also specify a default response code of 400 in the imposter declaration, so that anything that doesn't match a specific predicate will return a 400 response by default:
{
"port": "22001",
"protocol": "http",
"name": "login_user",
"defaultResponse": {
"statusCode": 400
},
"stubs": [
{
.... snip ....

Error when I'm trying to do a POST request in Fiware

I'm developing a script to do a POST request to Orion Context Broker of Fiware. The problem is that a receive an error:
"ContextLengthRequired"
, but I have Context-Length header in the request.
This is the error when I tried node fiware.js
{
"error":"ContentLengthRequired",
"description":"Zero/No Content-Length in PUT/POST/PATCH request"
}
This is the code in the file fiware.js:
var request = require('request');
var entity = {
"id": "Room6",
"type": "Room",
"temperature": {
"value": 23,
"type": "Float"
},
"pressure": {
"value": 700,
"type": "Float"
}
};
var jsonObject = JSON.stringify(entity);
var aux = jsonObject.toString();
aux = aux.length;
var peticion = {
url: "http://127.0.0.1:1026/v2/entities",
method: "POST",
headers: {
"Content-Length": aux,
"Content-Type": "application/json"
},
data: jsonObject
};
request(peticion, function(error, response, body) {
console.log(error);
console.log(body);
});
Change the variable peticion from this:
var peticion = {
url: "http://127.0.0.1:1026/v2/entities",
method: "POST",
headers: {
"Content-Length": aux,
"Content-Type": "application/json"
},
data: jsonObject
};
To this one:
var peticion = {
url: "http://127.0.0.1:1026/v2/entities",
method: "POST",
headers: {
"Content-Length": aux,
"Content-Type": "application/json"
},
body: jsonObject
};

swagger UI unable to process swagger.json that redoc is able to

I have the following simple swagger.json file. This is generated using go-swagger annotations for a golang service. I am able to get the UI page running with redoc.
I want to display it with swagger-ui but I cannot get it to work. It shows an error in console on the page load that says
Uncaught TypeError: Cannot create property 'definitions' on string 'swagger.json'(…)
window.swaggerUi = new SwaggerUi({
spec: "swagger.json",
dom_id: "swagger-ui-container",
supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'patch'],
onComplete: function(swaggerApi, swaggerUi){
log("Loaded UI")
},
onFailure: function(data) {
log("Unable to Load SwaggerUI");
},
docExpansion: "none",
jsonEditor: false,
defaultModelRendering: 'schema',
showRequestHeaders: false
});
window.swaggerUi.load();
Not sure why that is happening
The redoc page displays as follows
This is the swagger file
{
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"schemes": [
"http",
"https"
],
"swagger": "2.0",
"info": {
"description": "the purpose of this service is to do a health check",
"title": "Health Check API.",
"termsOfService": "TOS",
"contact": {
"name": "Backend",
"email": "Backend#company.com"
},
"license": {
"name": "Company Licence"
},
"version": "0.0.1"
},
"host": "host.com",
"basePath": "/",
"paths": {
"/health": {
"get": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"schemes": [
"http",
"https"
],
"summary": "Health check route.",
"operationId": "health",
"responses": {}
}
}
},
"definitions": {}
}
From SwaggerUI docs, it seems that it expects
A JSON object describing the OpenAPI Specification
as a value of spec parameter.
You should use url if you want to provide it with url:
window.swaggerUi = new SwaggerUi({
url: "swagger.json", // <----------------- change to url here
dom_id: "swagger-ui-container",
supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'patch'],
onComplete: function(swaggerApi, swaggerUi){
log("Loaded UI")
},
onFailure: function(data) {
log("Unable to Load SwaggerUI");
},
docExpansion: "none",
jsonEditor: false,
defaultModelRendering: 'schema',
showRequestHeaders: false
});
window.swaggerUi.load();

Not getting user data with google login

I have made a Google login with OAuth2.
The scope which I have used is userinfo. But I'm getting only the id from the object return.
I should get something like this:
{
"id": "<some-id>,
"email": "<correct-email-id>",
"verified_email": true,
"name": "blabla",
"given_name": "blabla",
"family_name": "blabla",
"link": "<link>",
"gender": "male",
"locale": "en"
}
But I only get :
{
"id": "<some-id>
}
I've tried:
https://www.googleapis.com/oauth2/v1/userinfo?access_token=<access-token>
https://www.googleapis.com/oauth2/v2/userinfo?access_token=<access-token>
and this is the call:
$.ajax({
type: 'GET',
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + accesstoken,
async: false,
contentType: 'json',
success: function(result) {
profileemail = result.email;
console.log(result);
},
error: function(e) {
console.log(e);
}
});
Make sure you request the profile scope. See:
https://developers.google.com/accounts/docs/OAuth2Login#obtaininguserprofileinformation

Resources