Zend setRawHeader - zend-framework

I have IndexController. I need to set raw header in indexAction.
I try to make
function indexAction(){
$this->getResponse()->setRawHeader('HTTP/1.1 404 Not Found');
}
But I see in Google chrome status 200 OK.
How set raw header?

To set a 404, use:
$this->getResponse()->setHttpResponseCode(404)
->setRawHeader('HTTP/1.1 404 Not Found'); // optional
If you don't explicitly set an HTTP response code, ZF will automatically send a 200 response if it was not overridden by setHttpResponseCode. Once it sends all the headers it checks to see if a response code was sent, and if not, sends a 200 regardless of your rawHeader.

Related

Axios get request always returns a blank response

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.

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).

How to return error message and HTTP status code together?

I'm using JAX-RS and I want to display the HTTP status and an error message.
Example: HTTP 204 No Content
Here is my code:
public Response getMessageById(#Context HttpServletRequest request,
#PathParam("idMessage") BigInteger idMessage){
if (idMessage== null){
return Response.status(HttpURLConnection.HTTP_NO_CONTENT)
.entity("No Content").build();
}
}
It displays No Content without the HTTP status.
HTTP defines a response header and a response body. The latter one is set by calling entity(), the former by status(). So what you actually send is this:
204 No Content
No Content
You just don't see the header if the tool you use does not display it by default. Use for example curl -v http://your-rest-service/api/resource so see it.
Furthermore:
Don't return 204 if an id is missing. This would rather be a 400 or 404 depending on the sematics. 204 is for operations that don't need to return anything (like PUT, POST, DELETE).
I doubt that this parameter can be null. JaxRS will not select the method if the request does not match the #Path.
Although using the constants in HttpURLConnection is possible, it would be more consistent to use javax.ws.rs.core.Response.Status
HttpServletRequest is for rare edge cases only. Don't use it if you don't need it.

What http return code should be if no data available

For example i have an api method /api/orders.getOrders which actually always exists.
If this method returns no data in following format, should i send 404 or 200 http response code?
{ "orders":[]
}
200 is correct.
From RFC 7231
The 4xx (Client Error) class of status code indicates that the client seems to have erred.
The 404 (Not Found) status code indicates that the origin server did not find a current representation for the target resource
In your case, the client did not make a mistake in asking for the resource; the origin server did find a current representation of the resource, so 404 (indeed, the entire 4xx class of responses) is not appropriate.
204 is also wrong.
The 204 (No Content) status code indicates that the server has successfully fulfilled the request and that there is no additional content to send in the response payload body.
"No content" means that the HTTP response message body is empty, which is to say the representation being returned is 0 bytes long. It's not appropriate when returning a non empty representation of an empty resource.

HTTP Response for Unsuccessful Handling of Request

Let's say I have a REST POST end-point: www.foo.com/id/X where X represents a number.
My server-side pseudocode looks like this:
performIdLookup(int id) {
if ( idExists(id) ) {
return toJson(lookup(id)) // returns 200/OK Status Code with object as JSON
}
else {
return HTTP_???_error
}
}
Per this question, sending a 400 error doesn't seem right here since the user submitted a valid request, but the server couldn't locate it.
What's the right HTTP response here and why?
That is very easy.
404 Not Found
If there is no resourece at /id/42, a resource can not be found for this URL.
See the list of HTTP status codes.
Not 400 (bad request). But 404 (not found). Yes, 404 is not what we are used to watching in these cases, but you can add some custom information with response.