how can I send response 404? - http-status-code-404

I have page that when it load it first check in the database if the page exist.
The problem is that if the page does not exist the page is load with Response 200.
Is there a way to send to the header Response 404 from HTML page?
Or Can I call to a function in CGI that will do it?
Thanks!

I assume your page is not just HTML as you check in your database.
You just need to send an HTTP header 404 :
(example in PHP)
<?php
ob_start(); // Turn on output buffering to be sure not to send anything before the header
(your code)
ob_end_clean(); // clean the output buffer
header("HTTP/1.0 404 Not Found"); // send the header
?>

Related

ionic laravel XMLHttpRequest cannot load

i am new to this and i am trying to login and get a token so the ionic and laravel can communicate. I am using satellizer and jwt on laravel. on post man i get the token back:
this is what i am getting loging in from ionic:
[enter image description here][2]
the error says:
XMLHttpRequest cannot load http://localhost:8000/api/authenticate. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.
and yeah, on my laravel side, i have included
header("Access-Control-Allow-Origin: *");
what am i missing here, thank you
There are many factors to why this happens. the error may happen because you have no access headers and the browsers gets this and blocks your requests.
It also happens when you your server experiences internal errors like 500,403,401 etc. you may have added headers to the requests life cycle(like in the middleware to filter all api requests) in your laravel app but sometimes an error 500 or even an echo or dd() interrupts the whole request life cycle and returns the errors WHICH the browser can't interpret through an ajax call and therefore it loses the headers you implicitly added thus the browser goes back to the preflight request error..
The only solution I suggest is proper error handling in your code and returning errors in a response and return it in json format.
public function someController extends Controller{
public function Foo(Request $request){
$input_bag = [
'some input' => first_$input,
'another important input' => $second_input,
];
$i = 0;
foreach ($input_bag as $key => $value) {
$value = trim($value);
if (empty($value)) {
$error_bag[$i] = "$key empty";
$i++;
} else {
//
}
}
//filter of false or null values
if (array_filter($error_bag)) {
return response()->json($error_bag, 400);
}
}
this returns a json response of the errors while running the code. and good use of try catches and returning the appropriate responses could make your debugging life easy.

Laravel RESTful returning 301 state

Mates,
I'm developing a Backbone/Laravel application.
When I try to send a POST request to a certain resource, it returns me 301 status with no response, regardless that on the controller i'm printing a 'hello world', to check if it's getting to that point.
Here's some code...
public function store()
{
//
return 'hello world';
}
This is the routes.php
Route::group(array('before' => 'auth'), function()
{
Route::get('/', 'SitesController#index');
Route::resource('rooms', 'RoomsController');
});
So, when I make a POST request to
rooms
With some info to save, it gives me back 301 status with no response at all.
Any idea what am I doing wrong?
Thanks in advance!
Solved!
On backbone collection configuration, I had url parameter with '/' at the end.
rooms/
Deleted that slash and now it works fine.
Hope someone find's this helpful
(Adding this answer in case anyone has the same issue as me)
In my case I had a resource videos which gave the exact same problem. The reason was that I also had a directory on the server /videos/ (with files in it) which the server tried to point me to before it let Laravel direct it to the controller.
For some reason, posting to "image" in Laravel, even without a trailing "/" gives me a 301 Moved Permanently HTTP response.
I don't have an "image" folder in my public directory and still don't understand why the redirect occurs.
Changing the request to "foo" seems to work fine.
So if you found this page because you're trying to store an image restfully, try something like this:
Route::resource('api/image', 'ImageController');

http-auth-interceptor is not settings the headers correctly

I have 2 issues using http-auth-interceptor. Let talk about the first one.
When the API return 401 (for the first time), the application is catching the event event:auth-loginRequired within a directive present in the index.html and display the modal so the user can login. Then on authentication success, the login script is calling authService.loginConfirmed(user, httpConfigCallback()). In the callback I'm setting 2 HTTP headers in order to update the API token. The problem is that I cannot see the header set when the initial request is dequeued. Here is my code:
$scope.user = UserAuthService.getUser();
// User is now auth, we confirm it
authService.loginConfirmed($scope.user, function(config){
config.headers["API_USER"] = $scope.user.guid;
config.headers['API_TOKEN'] = $scope.user.api_token;
return config;
});
But the header is not set:
The second issue I have is that the dequeued request is returning a 401, but the directive is not catching it anymore and so it's not displaying the login screen.
It's working well. The request header screenshot was the one from the OPTIONS request. It was denied by my server because I did not allowed my additional headers. I've added this:
$response->headers->set('Access-Control-Allow-Headers', "Origin,X-Requested-With,Content-Type,Accept,API_USER,API_TOKEN");
Now everything is working well.
Thanks
I suggest to use Angular interceptors to set your config headers.
Aa example: UserAuthInterceptor

How can CakePHP return a Mimetype header of JPG?

Found this:
http://stackoverflow.com/questions/7198124/setting-the-header-to-be-content-image-in-cakephp
but either not understanding, or its not working for me.
Basically want to record 'opens' for emails. Currently it "works" but in gmail it shows that an image is not being displayed--so I want to return an actual image header. I've tried doing:
$this->layout=false;
$this->response->type('jpg');
In the Controller for Opens, but that is not working.
Web Sniffer (http://web-sniffer.net/), is showing a jpeg response, but still have a blank no file found image. How can I fix?
[edit]
Thinking this:
http://stackoverflow.com/questions/900207/return-a-php-page-as-an-image
and this:
http://book.cakephp.org/2.0/en/controllers/request-response.html
might be solution
Serve a real image
If you only send the headers for an image, but don't send the image content - it will be considered a broken image. To send a file refer to the documentation for whichever version of CakePHP you are using. For example in 2.3+:
public function opened() {
...
$this->response->file('/path/to/1x1.gif');
return $this->response;
}
Pretty sure this worked:
$name = './img/open.jpg';
$fp = fopen($name, 'rb');
$this->response->header("Content-Type: image/jpg");
$this->response->header("Content-Length: " . filesize($name));
fpassthru($fp);
Where open.jpg is a 1x1 real pixel image in cakephp's /img directory.
Would love if someone else could confirm?
Getting:
����JFIF``��C $.' ",#(7),01444'9=82<.342��C 2!!22222222222222222222222222222222222222222222222222��"����������?����
Going to manually (so I'm guessing thats a "real" image file?). No longer getting gmails no image file icon.
nvermind--websniff says this is a html request. will update when I figure out.
[edit]
think this might be correct way:
$this->response->type('jpg');
$this->response->file('./img/open.jpg');
just tested, and definitely getting a 1x1 pixel download. No jibberish like above.
Gmails caching proxy
Normally serving a real image as suggest by AD7Six would be the way to go, however with Gmails caching proxy in place you may run into problems when just serving an image.
http://www.emailmarketingtipps.de/2013/12/07/gmails-image-caching-affects-email-marketing-heal-opens-tracking/
The problem is/was that the image has been cached, and the proxy wouldn't request it a second time, making tracking of opens unreliable.
Content length to the rescue
Until recently the workaround for this has been to respond with a content length of 0 (and private cache control which seems to be necessary for some other webmail providers):
// ...
$this->response->header(array
(
'Cache-Control' => 'private',
'Content-Length' => 0
));
$this->response->type('gif');
return $this->response;
This would return a response with no content body, which is treated as broken, however not all clients did actually show a broken image symbol, still it was recommended to hide the image using styles on the img tag.
Return of cache control
However it has been reported that Gmail made some changes recently so that sending a no-cache header is now being respected again.
http://blog.movableink.com/real-time-content-and-re-open-tracking-return-to-gmail/
So in addition to AD7Six example an appropriate Cache-Control header might now do the trick
// ...
$this->response->header(array
(
'Cache-Control' => 'no-cache, max-age=0'
));
$this->response->file('/path/to/1x1.gif');
return $this->response;

303 redirection not working with Angular HTTP POST

I am calling an authentication service where I do a $http.post which returns a 303 resonse, redirecting to a get call returning the response.
When I make the post call using Postman, I get the desired response but when I do an angular $http.post call, it returns me a 401 error (which is user not authorized)
Am I missing something while making the angular call? The backend service seems to work fine as it works fine on Postman.
This is how the $http call looks:
$http.post(url, userData).success(function(data, status) {
//handle success
}.error(function(data, status) {
//handle error
});
The url and the user data is constructed absolutely fine in this case.
The reason that you get a GET call is that the browser handle the 303 response before the angular can reach that. And the handling sequence is first go to the browser and then go to the angular framework.
So briefly what happens is : you make call to the server --> the server return the 303 response -> your browser handle the 303 and make a request to some url (should be 'location' in the response header) --> the server receive the request and return the 401 authorized response --> again the browser receive the 401 response first but this time the browser redirect the response to the angular --> at last you can receive the data and status inside the error().
The solution for this could be switching to other response status code like 2xx, and you can get the location from the body. Then you can do the redirection manually. If you HAVE to use 303 or other 3xx as the response code I don't think there's any effective solution at this moment because you can't do much to the browser. As far as I know there might be a solution at browser level but don't know when that will happen.
Hope this can help anyone has the similar issue like this although it has been nearly one year since this issue raised.
Some other ref: https://groups.google.com/forum/#!topic/angular/GKkdipdMbdo
There's similar solution you can see from the link above.
I faced this issue and I found a redirect url in error object after lots of hours struggle.
loginWithLinkedIn() {
let data = {
// some kind of information here
}
return this.http.get(`https://www.someurl.com/oauth/v2/authorization`).subscribe(res => {
console.log(res)
}, err => {
console.log(err.url) // here is the redirect url
window.location.href = err.url
})
}
Note: when you make a request and you get 303 response which is considered as error, that's why we think we are getting error but error contains useful info.

Resources