Return "text/plain" With Slim 3 - slim-3

I'm writing a route which should return a "text/plain" content type (only for this route).
$response->withHeader('Content-type', 'text/plain')->write("HELLO");
Am I doing it wrong? I keep on getting "text/html".

I'm assuming you do not return or re-assign the returned Response from the withHeader-method, because the default content type is text/plain.
The Response-object is immutable therefore only return a changed object on the withX-methods.
The solution is to return the response
$app->get('/foo', function($request, $response) {
return $response->withHeader('Content-Type', 'text/plain')->write('HELLO');
});

Related

i cannot save a response after execute the request using axios Instance (Pokedex - PokeApi)

I trying to do a pokedex using react and pokeAPI but when i try to save the response on a constant and return it this always return undefined.
c
try {
const pokemonResponse = getPokemonByName({
pokemonName,
})
console.log(pokemonResponse)
return pokemonResponse
} catch (e) {
throw new Error("Ups! We had a problem with product's fetch. Details: " + e)
}
}
here a codesandbox with the project
https://codesandbox.io/s/compassionate-haslett-ngv7z?file=/src/data/storage/PokemonStorage.ts
I found 2 issues in the code. See my fork on Codesandbox.
getPokemonByName returned undefined (because it didn't return anything). It should return Promise containing response from API I assume.
Compare it to getAllPokemons function in the same file that actually returns Promise.
Make sure you understand the arrow functions syntax.
Now you need to add await when calling getPokemonByName in async function. This will correctly assign result to pokemonResponse. See docs on async functions.

Find Object Array and its Properties from Ajax Post Request

I'm sending an AJAX request to an internal PHP and receiving back an object. The object has properties of "data" and "status", yet when I try to access them, it does not return anything. How can I show each property separately?
For reference, the returned obj array is:
{"data:[{"tagId":"8787","tagDescription":"001","tagMin":"0","tagMax":"100"},{"tagId":"8729","tagDescription":"1","tagMin":"44","tagMax":"555"}]
function GetAll() {
var PostRequest ={};
PostRequest['tagId']= 'all';
$.post('php here',PostRequest,ShowAllTags);
}
function ShowAllTags( responseData, responseStatus ) {
console.log(responseStatus);
var tagData = {};
tagData = responseData;
console.log(tagData['data']);
}
So according to the above comment mention by me, The problem is with json object, in response.
So first of all fix that,
Generic solution of this problem will be;
var obj = [{"tagId":"8787","tagDescription":"001","tagMin":"0","tagMax":"100"},{"tagId":"8729","tagDescription":"1","tagMin":"44","tagMax":"555"}];
obj.forEach(function(value, index){console.log(value.tagId)});
This might help, how to get value of each property

Json Web Token - jose4j - SyntaxError: Unexpected token e in JSON at position 0

I have a controller which tries to get a token.
I got this error in postman when I execute it in the view PRETTY
Unexpected 'e'
But if I go to the view RAW I can see the token like this.
eyJraWQiOiIxIiwiYWxnIjoiUlMyNTYifQ.eyJpc3MiOiJJc3N1ZXIiLCJhdWQiOiJBdWRpZW5jZSIsImV4cCI6MTQ3NTQ1OTMyNiwianRpIjoiTmF3d000bDVGRmFRZ0dBQkwzS3N5USIsImlhdCI6MTQ3NTQ1ODcyNiwibmJmIjoxNDc1NDU4NjA2LCJzdWIiOiJzdWJqZWN0IiwiZW1haWwiOiJtYWlsQGV4YW1wbGUuY29tIn0.f97SFDaAjUyUDK_UQgwgnCTewd0yw6tWK6DFLzpALFq177f1QMTYPbVdiIG1ViJ0FNJ6fUCleCd8BmrToUn25VSmRv799dtcz-xaN1kOgw90NQ00kPUhnDXG01-7hImkHfbmZZWORukP2yPK1sHWzpdjg9fJOvRZpZ6ZWli4HeuYRJqsFOv7PvwmGH9JnfRTf_2tboL-oAYBpT367eh60TggrvMgmrO_Taj5M7qGG0GpbwuVh_HTAkaKv7T2WmuZ2JPANhe5JvY_DDaqChtwd0IPREAhK3Xr-nTOIuwbQ0Y1hhOGfvDmikQj6DXnCERYixP6eR1dhC8n3bKvXyaVmA
This is the code of my controller.
#Path("/demo")
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response testMethod() throws JSONException, IOException {
RsaJsonWebKey rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048);
rsaJsonWebKey.setKeyId("k1");
JwtClaims claims = new JwtClaims();
claims.setIssuer("Issuer");
claims.setAudience("Audience");
claims.setExpirationTimeMinutesInTheFuture(10);
claims.setGeneratedJwtId();
claims.setIssuedAtToNow();
claims.setNotBeforeMinutesInThePast(2);
claims.setSubject("subject");
claims.setClaim("email","mail#example.com");
JsonWebSignature jws = new JsonWebSignature();
jws.setPayload(claims.toJson());
jws.setKey(rsaJsonWebKey.getPrivateKey());
jws.setKeyIdHeaderValue(rsaJsonWebKey.getKeyId());
jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
String jwt = jws.getCompactSerialization();
if(jwt == null){
return Response.status(204).entity(jwt).build();
}
return Response.status(200).entity(jwt).build();
}
I ignore the error in postman but I get the same error when try to execute it in Chrome.
I try to call my RESTful controller with angular like this, but I always get into the onError method with the message within the response parameter.
angular.min.js:118 SyntaxError: Unexpected token e in JSON at position 0
This is the code in angular
app.service('TokenService', function($http){
this.getToken = function(){
function onSuccess(response){
console.log('got it');
}
function onError(response){
console.log('fail');
}
return $http({
method : 'GET',
url : 'http:localhost:8080/rest/demo',
header: {'Content-Type' : 'application/json'}
}).then(onSuccess, onError);
}
}
My reference of the code for the token is from here with Jose4j
UPDATE
I solved this. I still think the way I did it initially it should work also, but I don't still understand why I get the error.
I created a pojo named Token with a property token as String then I changed this
return Response.status(200).entity(jwt).build();
to this:
Token token = new Token();
token.setToken(jwt);
return Response.status(200).entity(token).build();
This is my workaround to return a real json object.
I know it's much too late now, but I've faced the same problem and got it fixed with your solution, so Thanks.
Just for the sake of whoever came across this issue later. In my case I do it like this.
HashMap<String, String> credential = new HashMap<>();
credential.put("token", jwtToken);
apiResp = ResponseEntity.ok(jwtToken);
Btw, I also seem to figured out the problem which is Angular might expect that response from server is JSON object by default then parse it to JavaScript object for us.
So we got our error because we return string as a response entity and it can't parse string to an object. That's why putting the token in POJO solved it.
The other way around is setting return type from client-side like this.
login(username: string, password: string): Observable<any> {
let body = {username, password};
let res = this.http.post(
`${API.AUTHENTICATION}`, body, {
responseType: 'text'
});
return res;
}
Now, JS will know that the response is of string type and it won't try to parse it to an object anymore.

Unexpected token u in JSON at position 0

when I'm try to convert string to object I get error ``:
Unexpected token u in JSON at position 0
Service
setUser : function(aUser){
//sauvegarder User
localStorage.setItem('User', JSON.stringify(aUser));
},
getUser : function(){
//récuperer User
return JSON.parse(localStorage.getItem('User'));
}
The first thing to do is to look at what you're trying to parse. My guess is that you'll find it's "undefined", which is invalid JSON. You're getting undefined because you haven't (yet) saved anything to that key in local storage. undefined is then converted to the string "undefined" which JSON.parse can't parse.
I usually store and retrieve things in local storage like this:
Storing (just like yours):
localStorage.setItem("key", JSON.stringify(thing));
Retrieving (this is different):
thing = JSON.parse(localStorage.getItem("key") || "null");
if (!thing) {
// There wasn't one, do whatever is appropriate
}
That way, I'm always parsing something valid.
You are getting this error because you are not returning the response as a JSON string while your browser is expecting a JSON string to parse. Hence it is taking the first letter of your response string and throwing an error.
You can verify it by going to the networking tab of your browser's Dev tools and viewing the response.
To resolve this issue, you can use the code below in your http request.
var promiz = $http.post(url, data, {
transformRequest: angular.identity,
transformResponse: angular.identity,
headers: {
'Content-Type': undefined
}
});
Hope this helps!
I was also getting the same error. The problem was the response I was getting from HTTP Get Request was not in JSON format, Instead it was plain text.
this.BASE_URL = "my URL";
public getDocument() {
return this.http.get(this.BASE_URL)
.map((res: Response) => res.json())
.catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}
So, the JSON Parser was throwing an error.
When I map it into plain text like this:
.map((res: Response) => res.text());
It works.

415 (Unsupported Media Type) in $http.post method

I'm quite new to REST and AngularJS, but after several hours of googling I couldn't find any answer to my question:
I'm trying to do a POST request from my angularjs frontend to my backend implemented in java (using JPA).
When I'm trying to create a json-object and to do a POST I always get the 415 (Unsupported Media Type) error.
(Actually I don't even get "into" the scope of the service (i.E. "IN SERVICE" doesn't get printed to the console)..
If I add postData.toJSON(), it actually gets "POSTed", but arrives null ...
how do I have to format my 'postData' in Order to succesfully get POSTed?
(I also tried to write the Date-properties without ' " ' - no luck...)
Thank you for your help!
FrontEnd:
app.controller('WorkController', function($scope, $http) {
$scope.saveWork = function () {
var postData = {
"status" : "OPEN",
"startDate": "1338364250000",
"endDate": "1336364253400",
"WorkText" : "Test"
};
$http.post("http://localhost:8080/service/v1/saveWork", postData)
.success(function(data, status, headers, config){
console.log("IN SAVE WORK - SUCCESS");
console.log(status);
})
.error(function(){
console.log("ERROR IN SAVE WORK!");
})
}
});
Service:
#POST
#Consumes(MediaType.APPLICATION_JSON)
public Response save(WorkDto wo){
System.out.println("IN SERVICE");
if(ass == null){
System.out.println("Could nor persist work- null");
return Response.noContent().build();
} else{
Work workDao = WorkTransformator.transform(wo);
workDao.persist();
return Response.ok().build();
}
}
Instead of building and sending a parsed JSON object, create a javascript object and send that in your post body. You can reuse your postData object, but try removing the "" surrounding properties names.
Try this:
var postData = {
status : "OPEN",
startDate: "1338364250000",
endDate: "1336364253400",
workText : "Test"
};
UPDATE
Looks like the above doesn't work by itself. I thought that the Content-Type would be infered.
Can you try to do the post request this way :
$http({
method: 'POST',
url: 'http://localhost:8080/service/v1/saveWork',
data: postData,
headers: {
'Content-Type': 'application/json'
}}); // complete with your success and error handlers...
// the purpose is to try to do the post request explicitly
// declaring the Content-Type you want to send.
UPDATE 2
If this didn't work, compose a post request using Fiddler, and check what's the response.
Here's some pointers:
Download Fiddler2 if you dont already have it
Compose a request like in the screenshot below
You can then check on the pane on the left for what was the server response code. Double click that line (Ignore the error code on the screenshot...you should be getting a 415)
After double-clicking the response line, you can check and browse for more details on the right pane:
If you can successfuly post with a «manufactured» JSON object then the problem resides on your Angular code. If not, it's certainly something wrong with your Rest Service configuration.
You can also inspect the details of your POSTS made with the Angular app in Fiddler2. That should give you a good insight of what's going on.
If you're into it, you can then update your question with some screenshots of your Angular app requests. That will certainly help us to help you :)
I finally managed to find the cause of my error!
In my Rest-Service, I directly expected my java-class as parameter. (I thought this would be parsed/deserialized automatically). Quite naive I think... :)
In order to get it working I had to:
-Expect a String as Parameter in my #POST service
-Deserialize it (using GSON)
Here is the (now working) service:
#POST
#Consumes(MediaType.APPLICATION_JSON)
public Response save(String wo){
if(wo == null){
System.out.println("Could nor persist work- null");
return Response.noContent().build();
} else{
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HHmm:ssZ").create();
WorkDto dto = gson.fromJson(wo, WorkDto.class);
Work workDao = WorkTransformator.transform(dto);
workDao.persist();
return Response.ok().build();
}
}
Thanks again António for your help!

Resources