Hei guys,
for my webpage I wanted to implement some simple REST-Services to serve some Json.
To achieve that I created subfolder api and in this folder I created index.php and .htaccess file.
index.php uses AltoRouter to handle Routes called on /api.
.htaccess locks like following:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]
mod_rewrite is enable on my webhoster. (I was abelt to test this using some simple examples served by the webhoster)
I tested everthing on my local computer using localhost xampp.
Everthing is working fine. (GET and POST Requests)
After uploading this to my webpage I figured out, that POST Requests are Redirected to GET and therefore are not working.
Can anybody help with that issue. I need this POST Requests to be redirected to my index.php and be handled there to make some data update on my webpage.
Regards
Manuel
There is an update:
My Webhoster seams to use a nginx proxy that redirects to Apache.
POST seams to get coverted to GET and therefore my mechanism is not working anymore.
Can anyone tell me how to force nginx to redirect POST as POST?
Manuel
You can include the PHP file in your /api folder in your PHP file in your Root folder.
Just add the line include "./api/index.php" to your PHP in the Root folder.
Then the functions work in the PHP file in the /api folder, without having to open that specific PHP file in the /api folder.
https://www.php.net/manual/en/function.include.php
I am using Laravel sanctum in my project with angular as frontend. Getting unauthenticated from the second api request. Please let me know where am I going wrong
Frontend-> 127.0.0.1:4200
Backend-> localhost:8888
.env config
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=127.0.0.1
Added middleware auth:sanctum to the routes group in api.php
Ref: https://prnt.sc/rm9ejy
For anyone having an Unauthenticated error, please ensure you follow these steps.
Send a GET request to /sanctum/csrf-cookie
Send a post request to web route /login to get authenticated
After this step, you will be successfully authenticated by auth:sanctum middleware in the WEB route or any resource route that needs CRSF token present.
[Why did this work]
Sending a GET request(empty request) to /sanctum/csrf-cookie enables laravel to send the fresh set cookies command to your browser to set a fresh CRSF token which can be found in your cookies. Axios and most library send this fresh token as part of headers X-CSRF-TOKEN by default, for regular ajax request, please include them explicitly in your headers or in form _token, else your SPA will still hit the 419(token expired) error
Other things to be aware of:
Ensure your SESSION_DOMAIN is set to localhost
SANCTUM_STATEFUL_DOMAIN is set to your sub domain/SPA with the port e.g localhost:8000
For the original question please ensure you maintain same domain. I mean use localhost for both. And set SANCTUM_STATEFUL_DOMAIN = localhost:4200
Edited
Also set SESSION_DRIVER
Add your domains, for example
my API is running on localhost:8000 my client is running on localhost:3000 so my env setting looks like below
SANCTUM_STATEFUL_DOMAINS=localhost:8000,localhost:3000
also, add your session domain
SESSION_DOMAIN=localhost
Have you checked your Kernel.php? app/Http/Kernel.php
Make sure you uncomment \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, coz by default it is being commented
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
Two days of pain and despair to arrive at this conclusion: the Bearer token was not attached to the request, and that was because of my .htaccess configuration.
If you, like me, are not able to authenticate via API token, try to add this line on your .htaccess file in the public directory in your Laravel project:
RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
Right after RewriteEngine On directive.
CREDITS: Laravel not detecting auth token sent in the header and JWT package
From the screenshot you shared I see your domain is localhost and not 127.0.01, just do:
SANCTUM_STATEFUL_DOMAINS=localhost
For anyone using Laravel Homestead, use your actual domain.
SANCTUM_STATEFUL_DOMAINS=homestead.test
Which version are you running? Since V2.4.0 you need to specify the port:
SANCTUM_STATEFUL_DOMAINS=localhost:4200
See this issue for more info.
The sanctum stateful domains require the port number as well.
e.g. SANCTUM_STATEFUL_DOMAINS=127.0.0.1:4200
Although in your case your screenshot shows it should be SANCTUM_STATEFUL_DOMAINS=127.0.0.1:4201
Late in the game but just to help those that keep looking for this solution, most of the answers here have some truth, just have to put them together to make it work:
ENV file: SESSION_DOMAIN=localhost (or whatever your domains is)
in config->sanctum.php->stateful (if not already there): Sanctum::currentApplicationUrlWithPort()
in app/Http/Kernel.php API add as very first (this is important) : \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
in app/http/kernel API remove if there: \Illuminate\Session\Middleware\StartSession::class,
add to your api routes middleware: auth:sanctum
Also worth checking the guard settings under config->sanctum.php
that should do.
I had the same solution as Marco, adding the rewrite rule to my htaccess in public fixed it.
RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
FYI I am hosting this on Auzre Web App Service (linux), if anyone else is doing that.
check if you had changed your guard in past. goto config/auth.php check if your provider model is same as your user model (or the model you using) for authentication.
in my case i was using different guard and provider.
In case you have problems when going into production and/or have more than one subdomains and also use https don't forget that the port is 443 instead of the usual 80.
E.g.:
SANCTUM_STATEFUL_DOMAINS=*.example.com:443
SESSION_DOMAIN=.example.com
Lost days trying to figure out why the laravel, the spa or the android app were taking turns to fail, but never working all at the same time, until found that solution.
This worked for me. The solution is adding this to .htaccess of root folder (not only inside the public folder)
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
I have migrated a dynamic website (php, mysql) to a new host on a shared server plan.
The site is fully dynamic and has no fixed paths as such apart from the single entry point file "portal.php". The site exists as path-info to portal.php and is created from templates in a mysql database. There is no /portal directory, for example.
The homepage loads fine, but not subpages.The pathinfo is returned correctly, but the webserver is not translating it I guess:
http://example.com/portal/p/Logon = Fails with 404 error
http://example.com/portal.php/p/Logon = Works!
I have limited control over the apache server as the client has a basic, shared server plan.
I tried various options in a .htaccess file at the root of the website directory, but the best I could do was get an internal 500 error. At least I know the .htaccess is being read.
I'm hoping I can resolve this, otherwise I will have to migrate the site to a dedicated server instead.
Ok I found a solution. I see now why my initial post lacked information :)
I read this guide:
https://httpd.apache.org/docs/current/content-negotiation.html
And after trial and error, the following worked with a .htaccess file placed at root (I modified a html5boilerplate .htaccess file):
Options -Multiviews
RewriteEngine On
RewriteBase /
RewriteRule ^portal/(.*) /portal.php/$1
RewriteRule ^portal$ /portal.php
This is how I define my base URL:
$config['base_url'] = 'http://royalarcdevelopments.ca';
Now this is a live link you can test it yourself:
what happens is if i open this url using the path http://royalarcdevelopments.ca , royalarcdevelopments.ca it loads fine for both!
But when I load it using the URL www.royalarcdevelopments.ca I receive this error:
(index):1 Access to Font at 'http://royalarcdevelopments.ca/fonts/Poppins-Medium.ttf' from origin 'http://www.royalarcdevelopments.ca' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.royalarcdevelopments.ca' is therefore not allowed access.
now I know that my base URL is not using www so it throws the error to me!
My question is, how can we modify base URL so that it accepts a request from every path type!
Generally speaking, the www and non-www versions of the same domain are two different fully qualified domains.
Due to security reasons, some resources (like fonts in your particular case) violate the CORS policy - it results in the error you are receiving.
One solution would be to modify your web server's config so it allows the delivery of font files for cross origin requests.
A better solution would be (also from a SEO point of view) to redirect one of the domains to the other one, so you have only one "official" domain for your website. This can also be done from your web server's config or even from Codeigniter code, for example via some pre_controller hook. This way, when a visitor tries to access your secondary domain (let's say the www version in your particular case), it gets redirected to your primary domain (the non-www) and there is no more trouble with CORS.
Redirect as early as you can:
First, if you have access to the web server's configuration, implement redirection there;
Second, if you are using Apache as the web server, implement redirection in a .htaccess file;
If none of the above options are available for you, then do it from your application code.
I am trying to login with ajax to an API and I get this error:
XMLHttpRequest cannot load. The 'Access-Control-Allow-Origin' header
has a value that is not equal to the supplied origin. Origin
'http://localhost' is therefore not allowed access.
I read all about this error, all over the internet, and I've tried all the solutions I could find online. I modified the .htaccess and apache httpd configuration file according to the CORS instructions here: http://enable-cors.org/server_apache.html
Access-Control-Allow-Origin: *
Nothing seems to be working. I'd really appreciate if you guys can help me out with this. Thank you!
You have to set Access-Control-Allow-Origin header to * or specified value http://localhost
You can do this through:
1- Your code
2- .htaccess file
3- Server config (restart web server required)
Here is the link that show how to do it on apache
http://access-control-allow-origin-guide.com/enable-cors-on-apache-linux/
As added browser security, unless the API allows cross-browser origins in the the return responses header there is no way around this.
The browsers are blocking it, there is a plugin to allow for chrome but it is not realistic to depend on browser plugin to allow end user requests,
Try and reach out to the API provider and see if they can look into updating the header in the response.
It is a CORS issue:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
i use htaccess file for load JSON data in different hosting, and its works but
it have to put inside the public html root of our web hosting for example
uploading .htaccess into --> (https://freehostingsomewhere.com/)
then inside .htaccess
<FilesMatch "\.(ttf|otf|eot|woff|jpg|png|jpeg|gif|js|json|html|css)$">
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "http://localhost"
</IfModule>
</FilesMatch>
in here i use http://localhost to development and it works,
maybe if i have another web host just change it into that url, i will try it later (it can, i already try it) :p
this is just for more clear explanation
cheers :p
Are your requests using either cookies or authorization by any chance?
Check on your ajax call on the client side if you're configuring it to be done "with credentials"
.withCredentials = true;
If yes, the wildcard(*) will not work and you'll need to provide the exact host as the value for Access-Control-Allow-Origin.
Refer to this stack overflow answer or Mozilla Documentation on CORS