Axios get request always returns a blank response - axios

I launched my app on heroku.
And ever since all of my axios get request return a blank html.
axios.post(process.env.REACT_APP_baseServerurl + '/create/get-users')
axios.get(process.env.REACT_APP_baseServerurl + '/create/get-users')
the response i get is always blank.
request
response
but if i change the same request to a post it works fine.
The get request works fine when i try it on my localhost. But when i deploy it on heroku it returns blank.
router.post('/get-users', (req,res) => {
res.json("asdsadas")
})
router.route('/get-users').get((req,res) => {
res.json("yes")
})
the POST request works but GET request returns a 304.

The 304 HTTP Status code means that the resource has not been modified since the last get request. This indicates that the server thinks you already have a copy of up-to-date data. The Server makes this assumption by looking at the If-None-Match and If-Modified-Since in your request header. (https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_redirection)
These are the actions you could take:
Cache the data manually on your first successful request (if there is one, otherwise there must be an error in the usage of the If-None-Match and If-Modified-Since headers) and re-use the cached data if the server returns a 304 status code.
Disable the mechanism and live with the fact that you might request the same data the server already gave you.

Related

Forwarding a response from another server using JAX-RS

I have an angular client which is making a POST call to my server. This server needs to get a response by calling another server(server2) with a POST call and pass the response from the server2 to the client. I tried the following approaches.
public Response call(){
String server2Url = "http://server2/path"
RestClient restClient = new RestClient();
return Response.fromResponse(restClient.post(server2Url)).build();
}
But in the above case the HTTP status code gets transferred but not the response body. The response body is empty
Then I tried:
public Response call() throws URISyntaxException{
String server2Url = "http://server2/path"
RestClient restClient = new RestClient();
return Response.temporaryRedirect(new URI(server2Url)).build();
}
but the browser client ends up making an OPTIONS call to the server2Url instead of a POST
and I tried.
public Response call() throws URISyntaxException{
String server2Url = "http://server2/path"
RestClient restClient = new RestClient();
return Response.seeOther(new URI(server2Url)).build();
}
but this ends up making a GET call instead of a POST.
How do I make the browser client make a POST call to server2
You can use Html Client from JAX-RS to make your own requests (from server1 to server2) and then return the response from server2 to the angular client.
public Response call() {
String url = "server2 url";
Response response;
try {
response = ClientBuilder
.newClient()
.target(url)
.request()
.post(Entity.json(null), Response.class);
}
catch (Exception e) {
// Whatever you want
return null; // or error
}
// Return the status returned by server 2
return Response.status(response.getStatus()).build();
}
What you are trying to accomplish is covered in the RFC 2616 I just found here.
If the 302 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.
So it looks like this is out of your hands if you´re not implementing the client.
Edit because I was told that RFC 2616 must not be used any longer.
RFC 7231 states that:
302 Found
The 302 (Found) status code indicates that the target resource
resides temporarily under a different URI. Since the redirection
might be altered on occasion, the client ought to continue to use the
effective request URI for future requests.
The server SHOULD generate a Location header field in the response
containing a URI reference for the different URI. The user agent MAY
use the Location field value for automatic redirection. The server's
response payload usually contains a short hypertext note with a
hyperlink to the different URI(s).
Note: For historical reasons, a user agent MAY change the request
method from POST to GET for the subsequent request. If this
behavior is undesired, the 307 (Temporary Redirect) status code
can be used instead.
What is:
307 Temporary Redirect
The 307 (Temporary Redirect) status code indicates that the target
resource resides temporarily under a different URI and the user agent
MUST NOT change the request method if it performs an automatic
redirection to that URI. Since the redirection can change over time,
the client ought to continue using the original effective request URI
for future requests.
The server SHOULD generate a Location header field in the response
containing a URI reference for the different URI. The user agent MAY
use the Location field value for automatic redirection. The server's
response payload usually contains a short hypertext note with a
hyperlink to the different URI(s).
Note: This status code is similar to 302 (Found), except that it
does not allow changing the request method from POST to GET. This
specification defines no equivalent counterpart for 301 (Moved
Permanently) ([RFC7238], however, defines the status code 308
(Permanent Redirect) for this purpose).

HTTP GET Request Status 204 Vs 404

I have 2 resources User and Album. A user has a list of albums. To get albums there are 2 REST API.
user/{userId}/albums/{albumId} gets album by albumId. If not found returns 404
user/{userId}/albums gets all albums by userId. In this case, if a user has no albums, what should be the status code 204 or 404?
Is the absence of any album really seen as an error? Assuming the albums are returned as a JSON array, the common response to such a situation would be a HTTP 200 with an empty array as the body.
Returning 404 signals that the resource doesn't exist, kind of saying that it isn't even possible to ask for the list of albums for this particular user. But in fact, it's possible to successfully return the list of albums, it's just that the list is empty. It doesn't seem at all exceptional to me. This is completely in contrast to retrieval of one specific album using an ID that doesn't exist (using your other endpoint); in such a situation a 404 is correct.
While a 204 seems better than a 404, because it at least tells the client that the request was successful but had no content, its intention is not really to be used to signal a "successful absence". Rather, it signals that the resource DOES exist but for some reason the server chose not to include the resource in the response body - for example the purpose of the request could have been to simply pass back some headers to the client.
A 204 can also be used as a response to a POST request where some action was carried out by the server without necessarily creating any new resource (which would have implied a 201 CREATED), or where it's for some other reason not relevant to return any resource.
I think it's clear that what you need is a
GET /user/xxx/albums
HTTP/1.1 200 OK
[]
Here is what the RFC2616 that defines the HTTP protocol says about Status-codes:
The first digit of the Status-Code defines the class of response. The last two digits do not have any categorization role. There are
5 values for the first digit:
- 1xx: Informational - Request received, continuing process
- 2xx: Success - The action was successfully received,
understood, and accepted
- 3xx: Redirection - Further action must be taken in order to
complete the request
- 4xx: Client Error - The request contains bad syntax or cannot
be fulfilled
- 5xx: Server Error - The server failed to fulfill an apparently
valid request
In your case, the request was successful, but there are no albums to show, so you definitely should use a status from the 2xx category.
Here is what the RFC says about the 204 status:
10.2.5 204 No Content
The server has fulfilled the request but does not need to return an
entity-body, and might want to return updated metainformation. The
response MAY include new or updated metainformation in the form of
entity-headers, which if present SHOULD be associated with the
requested variant.
If the client is a user agent, it SHOULD NOT change its document
view from that which caused the request to be sent. This response
is primarily intended to allow input for actions to take place
without causing a change to the user agent's active document view,
although any new or updated metainformation SHOULD be applied to
the document currently in the user agent's active view.
The 204 response MUST NOT include a message-body, and thus is
always terminated by the first empty line after the header fields.
The RFC states that the 204 is primarily intended to allow inputs, so you shouldn't use this one. I would use the 200 in this case.
Error Code 404
The web site hosting server will typically generate a "404 Not Found" web page when a user attempts to follow a broken or dead link.
Return Code 204
The server has fulfilled the request but does not need to return an entity-body.
Conclusion
You obviously need to return a 204 status code. If you use the 404 one, the user may be disturbed. More, you use 404 when the targeted album doesn't exist. Using 404 for both 1 and 2 is illogical.
When you ask for a specific resource, say a user, and the user doesn't exist, then you should return 404. For example, you have an API to retrieve a user using the following URL:
https://yourdomain.com/api/users/:userid
and a request is made to retrieve user 1234, that doesn't exist, then you should return 404. In this case, the client requested a resource that doesn't exist.
https://yourdomain.com/api/users/1234
404
Now suppose you have an api that returns all users in the system using the following url:
https://yourdomain.com/api/users
If there are no users in the system, then, in this case, you should return 204.
Let me give my 2 cents on this. I hope you already know the difference between 404 vs 204.
The scenario i would prefer to use each status code are :
404 Status Code
404 means that the Resource not found or doesn't exist or URL is invalid
For example
GET : https://api.myapp.io/product/product_id_123
GET : https://api.myapp.io/image/nokia.jpg
If the single product / resource item doesn't exist in database or in resource folder, that means the resource of this URL is invalid so we have to throw 404 and Search Engines like Google & bing will not going to cache the result and will not retry again the next day for fresh content.
204 Status Code
204 means that the URL is valid and Server has successfully did the execution but it has no data to return.
For example
GET : https://api.myapp.io/product/search?keyword=nokia
If there is no data matched (single or multiple) for the keyword in database to return back the results, then throw 204 because there is no data to return but the URL is still valid and Search Engines like Google & bing will retry again the next day for fresh content because for them it is not invalid url and when you retry the next day there might be some data which matches the query.
I agree with the responses, but I think is 204 or 200, it depends of your response when the album list is empty.
If you will return a empty array, the return it with 200 code, if you prefer to don't return anything, then the right one will be 204. (I prefer a 200 with empty list)
Only use 404 with a resource doesn't existis, if it is a empty list the choose 204 or 200.
Good hacking man!

Passing parameters in BODY with GET request

I want to pass some data within request body, but I'm using GET request, because I just want to modify this data and send it back.
I know that it is bad practice to use body with GET requests.
But what should I do with this situation if I want to build correct RESTful service?
P.S. I'm not changin any object on server.
I'm not putting any new object on server.
You want a POST. Something like
POST /hashes
{
"myInput": ...
}
The response would be the hashed value. There's no rule that the created resource must be retained by the server.
From the RFC:
The action performed by the POST method might not result in a
resource that can be identified by a URI. In this case, either 200
(OK) or 204 (No Content) is the appropriate response status,
depending on whether or not the response includes an entity that
describes the result.

Single request to jetty interpreted twice with http error code 401

When I send GET http requests to an EJB served by jetty, I often get a 401 response even though the auth parameters are correct.
When I look into jetty logs I see this :
2013-06-27 11:54:11.004:DBUG:oejs.Server:REQUEST /app/general/launch on AsyncHttpConnection#3adf0ddc,g=HttpGenerator{s=0,h=-1,b=-1,c=-1},p=HttpParser{s=-5,l=34,c=0},r=1
2013-06-27 11:54:11.021:DBUG:oejs.Server:RESPONSE /app/general/launch 401
2013-06-27 11:54:11.066:DBUG:oejs.Server:REQUEST /app/general/launch on AsyncHttpConnection#3adf0ddc,g=HttpGenerator{s=0,h=-1,b=-1,c=-1},p=HttpParser{s=-5,l=102,c=0},r=2
I suspect that the request is not fully read (too large request entity or too large headers?)
as it is parsed twice for a single request. Is there a way to fix this ?
what does HttpParser{s=-5,l=34,c=0} and HttpParser{s=-5,l=102,c=0} mean ?
when I desactivate authentication (security constraints using simple jetty realm). the request is only parsed once.
401 means that the server requires authentication credentials that the client either has not sent or the ones sent by the client have not been authorized.
Some client implementations will resend the request if they receive a 401 including the credentials. If your client is doing that, that would explain why you get the request twice on the server.
The HttpParser toString() method returns the current status of the HttpParser. Here's the code:
return String.format("%s{s=%d,l=%d,c=%d}",
getClass().getSimpleName(),
_state,
_length,
_contentLength);
So s is the state. -5 is STATE_HEADER. And l and c represent the length and the contentLength.

Picking HTTP status codes for errors from REST-ful services

When a client invokes my REST-ful service, it needs to know if the response came back was 'from me' or rather a diagnosis from the containing web server that something awful happened.
One theory is that, if my code is called, it should always return an HTTP OK(=200), and any errors I've got to return should be just represented in the data I return. After all, it's my code that gets the response, not the naked browser.
Somewhat self-evidently, if I'm using REST to generate HTML read directly by a browser, I absolutely must return an error code if there's an error. In the case I care about, it's always Javascript or Java that is interpreting the entrails of the response.
Another possibility is that there is some family of HTTP status codes that I could return with a high confidence that it/they would never be generated by a problem in the surrounding container. Is this the case?
I use the following:
GET
200 OK
400 Bad Request (when input criteria not correct)
POST
202 Accepted (returned by authorization method)
401 Unauthorized (also returned by authorization)
201 Created (when creating a new resource; I also set the location header)
400 Bad Request (when data for creating new entity is invalid or transaction rollback)
PUT
Same as POST
201 Ok
400 Bad Request
DELETE
200 OK
404 Not Found (same as GET)
I would not know how to avoid that some container returns codes like 404.
4xx codes are meant to handle client errors along with possibly some entity that describes the problem in detail (and thus would mean a combination of both of your mentioned approaches). Since REST relies on HTTP and the according semantics of status as well as methods, always returning 200 in any possible case is a violation of this principle in my opinion.
If you for instance have a request such as http://foo.com/bar/123 which represents a bar ressource with id=123 and you return 200 with some content, the client has no chance to figure out if this was the intended response or some sort of error that occured. Therefore one should try to map error conditions to status codes as discussed in REST: Mapping application errors to HTTP Status codes for example.