export const login = () => {
return async (dispatch) => {
try {
const response = await fetch(
`https://simplyrem.com/srwl/haib/index.php`,
{
method: 'POST',
headers: {
accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
auth: 'XCXCXCXCX',
usernamex: 'XXXXX',
passwordx: 'XXXXXXXX',
}),
}
)
if (!response.ok) {
const errorResData = await response.json()
console.log(errorResData)
throw new Error('Something went wrong!')
}
const responseData = await response.json()
const userInfo = responseData
console.log(userInfo)
dispatch({
type: LOGIN,
userInfo: userInfo,
})
} catch (err) {
throw err
}
}
}
Hello all,
I have tested this API using insomnia while inputting my credentials and I got a JSON response back, so I know that the API works and my credentials are correct. I am new to React Native and I don't know if I'm adding the parameters correctly by using body: JSON.stringify... Obviously, I've replaced the information with "X"s. In swift, I was able to also get a response back, but when I'm trying to recreate the API call in react-native I get error
> [Unhandled promise rejection: SyntaxError: JSON Parse error: Unexpected EOF]
> * [native code]:null in parse
> - node_modules/react-native/node_modules/promise/setimmediate/core.js:37:13 in tryCallOne
> - node_modules/react-native/node_modules/promise/setimmediate/core.js:123:24 in setImmediate$argument_0
> - node_modules/react-native/Libraries/Core/Timers/JSTimers.js:130:14 in _callTimer
> - node_modules/react-native/Libraries/Core/Timers/JSTimers.js:181:14 in _callImmediatesPass
> - node_modules/react-native/Libraries/Core/Timers/JSTimers.js:441:30 in callImmediates
> - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:387:6 in __callImmediates
> - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:135:6 in __guard$argument_0
> - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:364:10 in __guard
> - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:134:4 in flushedQueue
> * [native code]:null in flushedQueue
> * [native code]:null in invokeCallbackAndReturnFlushedQueue >
JSON Parse error: Unexpected EOF it's usually
an error when you are trying to convert the non-covertable response to json (like Html response) into json
for safety I usually convert it first to string using .then(res => res.text()) then console.log() or alert() it to prove the response is Convertable to json or not without showing the react-native's red-box message,
if the response is valid json you can convert it by yourself with JSON.parse(responseText)
example like
fetch( "https://simplyrem.com/srwl/haib/index.php", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
Email: 'XXXXX',
password: "xxxxx",
}),
})
.then((response) => response.json())
.then((responseJson) => {
if (responseJson.IsSuccess) {
console.log(responseJson);
alert(responseJson)
} else {
console.log(responseJson.ErrorMessage);
alert(responseJson.ErrorMessage)
}
})
.catch((error) => {
alert(error);
});
Related
In the following postman pre request script, I need to call multiple requests before I make an actual postman request.
Firstly, it will call session API to retrieve the session id
After session id is success only, then I need to call customer signon to make the user logged in.
So I did the following changes in my postman prerequest script but some how the LocalSessionId in the customer signon request is undefined.
const sessionRequestData = {
url: "http://myurl.com/session",
method: 'POST',
header: { 'content-type': 'application/json' },
body: {
mode: 'raw',
raw: JSON.stringify({
"device": {
"id": "web",
"type": "WEB"
}
}
};
pm.sendRequest(sessionRequestData, function (err, res) {
var jsonData = res.json();
if (err) {
console.log("mailman: error retrieving session id"+err);
}
else {
console.log("mailman: retrieved session data succesfully"+ jsonData.session.id);
pm.variables.set("LocalSessionId", jsonData.security.session.id);
}
});
const customerSignonRequestData = {
url: "http://myurl.com/CustomerSignOn",
method: 'POST',
header: { 'content-type': 'application/json' },
body: {
mode: 'raw',
raw: JSON.stringify( "customerRequest": {
"identities": {
"identity": [
{
"data": "sessionId",
"value": `${pm.variables.get("LocalSessionId")}`
}
]
}
});
pm.sendRequest(customerSignonRequestData, function(err, res){
console.log("customer sign on request "+ JSON.stringify(customerSignonRequestData.body.raw))
var jsonData = res.json();
if (err) {
console.log("mailman: unable to signon"+err);
} else {
console.log("mailman: login successful"+ JSON.stringify(jsonData))
}
});
Can anyone suggest how can I make sure that the customer signon is called after the session is retrieved only.
I'm currently trying to debug a react-native package (react-native-uploader) I'm using to try and upload a bundle of files (photos). Despite working on ios, the current implementation is returning the following error for android:
Response{protocol=http/1.1, code=405, message=Method Not Allowed, url=${config.apiBase}/load/${this.props.id}/uploadconfirmation}
The error is originating from this line in the package:
Response response = client.newCall(request).execute();
Where the client is:
private final OkHttpClient client = new OkHttpClient()
Where request is:
Request{method=POST, url=${config.apiBase}/load/${this.props.id}/uploadconfirmation, tag=null}
I've successfully made posts to the endpoint using formdata:
let tData = new FormData();
const that = this;
tData.append("confirmation_doc", {
uri: files[0].filepath,
type: "image/jpeg",
name: "confirmation_doc.jpg",
});
axios.post(
`${config.apiBase}/load/${this.props.id}/uploadconfirmation`,
tData
)
.then(response => {
Alert.alert(
"Success",
"Uploaded Successfully!",
[{ text: "OK", onPress: () => that.props.close() }],
{ cancelable: false }
);
});
I've tried looking through the source code to determine where things are falling apart and it seems like everything is posting as it should (headers look good, method looks good, endpoint looks good). I'm not all too familiar with Java so any input would be appreciated.
HTTP 405 Method Not Allowed ... is a client-side error.
The method received in the request-line is known by the origin server but not supported by the target resource.
if the JavaScript works, but the Java won't... you might be looking for the MultipartBuilder
... in combination with MediaType.FORM.
In order to solve this issue, I had to abandon the react-native-uploader package I had been using. Below is how I managed to resolve the issue:
let tData = new FormData();
this.state.selectedImages.forEach((item, i) => {
tData.append("doc[]", {
uri: item.uri,
type: "image/jpeg",
name: item.filename || `filename${i}.jpg`,
});
});
fetch(`${config.apiBase}/load/${this.props.id}/uploadconfirmation`, {
method: "post",
headers: {
Accept: "application/x-www-form-urlencoded",
Authorization: `Token ${this.props.token}`,
},
body: tData,
})
.then(res => res.json())
.then(res => {
Alert.alert(
"Success",
"Uploaded Successfully!",
[{ text: "OK", onPress: () => that.props.close() }],
{ cancelable: false }
);
})
.catch(err => {
console.error("error uploading images: ", err);
});
I am working with springmvc and angularjs. I'm trying to send the String response from springmvc controller to the angular controller, but facing the below error message shown on the browser console and the response which returned from springmvc is not getting printed in the angularjs side.
ERROR:
SyntaxError: Unexpected token s in JSON at position 0
at JSON.parse ()
Sample code:
js:
myApp.controller('myTestCtrl', function ($rootScope, $scope,MyService) {
$sco[e.submitInfo = function(){
var data = new FormData();
var allInfo =
{
'name': $scope.name,
'id': $scope.id,
'product': $scope.product,
'message':$scope.message
}
//files to be attached if exists
for (var i in $scope.filesAttached) {
var file = $scope.filesToAttach[i]._file;
data.append("file", file);
}
MyService.sendAllInfo(data).then(
function (response) {
if (response === "") {
alert("success");
//logic
}else{
alert("in else part " + response);
}},
function (errResponse) {
console.log("Error while retrieving response " + errResponse);
});
};
});
}});
MyService:
myService.sendAllInfo = function (data) {
var deferred = $q.defer();
var repUrl = myURL + '/myController/allInfo.form';
var config = {
headers: {'Content-Type': undefined},
transformRequest: []
}
$http.post(repUrl,data,config)
.then(
function (response) {
alert("response json in service: "+ response);
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while getting response.data'+ errResponse);
deferred.reject(errResponse);
}
);
return deferred.promise;
};
Spring mvc:
#RequestMapping(value = "/allInfo", method = RequestMethod.POST, produces = MediaType.TEXT_PLAIN_VALUE)
public #ResponseBody
String allInfoData(#RequestParam("data") String data,#RequestParam("file") List<MultipartFile> files){
//logic
return "success";
}
In my above spring controller code, i'm returning success string to angularjs controller, but in the browser the below error is displayed.
SyntaxError: Unexpected token s in JSON at position 0
at JSON.parse ()
Note: Above is only the sample code , it is perfectly hitting the spring controller and issue is only while catching the response from spring controller to angular controller.
I tried to change produces=MediaType.TEXT_PLAIN_VALUE to produces={"application/json"} but still it is showing the same error.
To avoid parsing the string, use transformResponse: angular.identity:
myService.sendAllInfo = function (data) {
̶ ̶v̶a̶r̶ ̶d̶e̶f̶e̶r̶r̶e̶d̶ ̶=̶ ̶$̶q̶.̶d̶e̶f̶e̶r̶(̶)̶;̶
var repUrl = myURL + '/myController/allInfo.form';
var config = {
headers: {'Content-Type': undefined},
transformRequest: [],
//IMPORTANT
transformResponse: angular.identity
}
var promise = $http.post(repUrl,data,config)
.then(
function (response) {
alert("response json in service: "+ response);
return response.data;
},
function(errResponse){
console.error('Error while getting response.data'+ errResponse);
throw errResponse;
}
);
return promise;
};
Also avoid using the deferred Anti-Pattern.
In the response there are some values which are simple text not String so You're asking it to parse the JSON text something (not "something"). That's invalid JSON, strings must be in double quotes.
If you want an equivalent to your first example:
var s = '"something"';
var result = JSON.parse(s);
The best solution is use responseType: "text" as "json" it will woke
I'm sending a get request from an angularjs 1.5x client to a Java HTTP method and in the client I will print the response which will contain some JSON data.
// method from an angular service that sends ajax requests
this.getTask = function(taskName) {
var url = 'http://localhost:9998/tasks/' + taskName;
var config = {
headers: {
'Content-Type': 'application/json'
}
};
$http.get(url, config)
.then(function successCallback(response) {
console.log(response.data);
}, function errorCallback(response) {
console.log(response);
});
};
The request executes successfully but when the statement response.data does not return the JSON data but it instead returns this;
Object { data: Object, status: 302, headers: headersGetter/<(), config: Object, statusText: "Found" }
Usually that statement would print out the data Object contained in the object above. What is going wrong?
var data = JSON.parse(apiResponse);
var name = data.response;
I am trying to connect a Java REST service to a ExtJs JSONP request but even though the java method executes I haven't been able to get a response test. This is what I am trying:
Java Code:
#Path("/hello")
public class Hello {
#GET
#Produces("text/javascript") // have also tried application/json
public String sayJsonHello(#QueryParam("_dc") String dcIdentifier, #QueryParam("callback") String callback) {
System.out.println(callback);
callback += "({\"success\":true, \"msj\":" + "\"" + "Exitoooo!" + "\" });";
System.out.println(callback);
return callback;
}
}
ExtJs code:
Ext.data.JsonP.request({
url: "http://10.1.50.66:7001/Simulador/webresources/hello",
params: {
},
callback: function (response) {
console.log(response); //true
console.log(response.result); //undefined
console.log(response.responseText); //undefined
console.log(response.success); // undefined
if (response.success === true) {
Ext.Msg.alert('Link Shortened', response.msj, Ext.emptyFn);
} else { // entering here :( why ?
Ext.Msg.alert('Error', response.msj, Ext.emptyFn);
}
}
});
response is printting true, everything else undefined :(
callback looks like this Ext.data.JsonP.callback1({"success":true, "msj":"exito"})
Any ideas what could be wrong?
Ok this worked out for me:
Ext.data.JsonP.request({
url: "http://10.1.50.66:7001/Simulador/webresources/hello",
callbackKey: 'callback1',
params: {
},
success : function(response) {
console.log("Spiffing, everything worked");
// success property
console.log(response.success);
// result property
console.log(response.result);
console.log(response.msj);
},
failure: function(response) {
console.log(response);
Ext.Msg.alert('Error', 'Please try again.', Ext.emptyFn);
}
});