net::ERR_CONNECTION_REFUSED using Laravel 9, ReactJs with vite js - php

I'm trying to build an app using Laravel 9 and ReactJS with vite js. I tried following command to build.
npm run dev
But I'm getting following errors,
GET http://[::1]:5173/resources/css/app.css net::ERR_CONNECTION_REFUSED
GET http://[::1]:5173/#vite/client net::ERR_CONNECTION_REFUSED
GET http://[::1]:5173/resources/js/app.jsx net::ERR_CONNECTION_REFUSED
GET http://[::1]:5173/#react-refresh net::ERR_CONNECTION_REFUSED

If you entered npm run build on production, your .env file looks good and you still have such errors as the author just delete hot file in public directory

This means that your assets are not built yet, use npm run build.

In my case the issue was that the port 5173 was already in use.
I've just freed it - and everything worked again. Hope that helps.

Its Work for me
1-First Run npm run dev in Terminal
2-Then Run npm run build

I think I may have found a solution with the build option called Rollup.
When building in production, rollup will remove unused code. In this process it will bundle the required assets and reference them in accordance to the URL that you would be using at that current moment.
To fixed it, you could try this:
export default defineConfig({
build: {
rollupOptions: {}
}
})
I was helped by a similar issue posted on Github so maybe you could use that as a point of reference.
Here is the Discussion

build assets before uploading your project in live server or cpanel
you can use this code - npm run build
you can see some change in your project folder after build assets file.
assets file will come to this folder - public->build

add host in your vite.config.js, so it will force it to IPv4
export default defineConfig({
server: {
host: '127.0.0.1', // Add this to force IPv4 only
},
plugins: [
laravel({
input: ['resources/css/app.css', 'resources/js/app.js'],
refresh: true,
}),
],
});

Local is working fine for me, try adding this to vite.config.js file:
server: { cors: false },
or (try adding and mixing all values)
server: { https: false, cors: false, hmr: false, port: 8000 },

Related

What should be run in a container for a PHP-based Docker AWS lambda?

PHP isn't a natively supported language in AWS Lambda, but I thought I'd try my hand at getting one working, using a custom Docker image. I am using this official AWS example to structure the image.
I don't quite understand the pieces yet. I will add what files I have to this post.
Firstly, my Dockerfile:
# Demo of a PHP-based lambda
#
# See example:
# https://github.com/aws-samples/php-examples-for-aws-lambda/blob/master/0.7-PHP-Lambda-functions-with-Docker-container-images/Dockerfile
FROM php:8.0-cli-alpine
WORKDIR /root
# Install Composer
COPY bin bin
RUN sh /root/bin/install-composer.sh
RUN php /root/composer.phar --version
# Install Composer deps
COPY composer.json composer.lock /root/
RUN php composer.phar install
# Install runtimes
COPY runtime /var/runtime
COPY src /var/task/
# Entrypoint
CMD ["index"]
Based on the example I also have:
A PHP listener program at /var/runtime/bootstrap (nearly verbatim copy of the example repo)
Composer dependencies at /root/vendor/... that are loaded by the bootstrap
A trivial index file at /var/task/index.php (verbatim copy of the example repo)
One change I have made is to base the image on an Alpine image from PHP, rather than to use an Amazon Linux image. I wonder, could there be something in the Amazon image that is needed?
The test I am using is the "hello world" in the AWS Lambda UI:
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
Anyway, I have used docker login and docker push to get the image to ECR. When I run the hello world test inside the AWS dashboard, I am getting this set of error logs in CloudWatch:
2021-11-13T19:12:12.449+00:00 IMAGE Launch error: fork/exec /usr/local/bin/docker-php-entrypoint: permission denied Entrypoint: [docker-php-entrypoint] Cmd: [index] WorkingDir: [/root]
2021-11-13T19:12:12.493+00:00 START RequestId: 38da1e10-4c93-4109-be10-32c58f83a2fb Version: $LATEST
2021-11-13T19:12:12.502+00:00 IMAGE Launch error: fork/exec /usr/local/bin/docker-php-entrypoint: permission denied Entrypoint: [docker-php-entrypoint] Cmd: [index] WorkingDir: [/root]
2021-11-13T19:12:12.504+00:00 END RequestId: 38da1e10-4c93-4109-be10-32c58f83a2fb
2021-11-13T19:12:12.504+00:00 REPORT RequestId: 38da1e10-4c93-4109-be10-32c58f83a2fb Duration: 9.20 ms Billed Duration: 10 ms Memory Size: 128 MB Max Memory Used: 3 MB
2021-11-13T19:12:12.504+00:00 RequestId: 38da1e10-4c93-4109-be10-32c58f83a2fb Error: fork/exec /usr/local/bin/docker-php-entrypoint: permission denied Runtime.InvalidEntrypoint
That makes a lot of sense, as I don't understand the entry point of "index" either, but it's there as a CMD in the example Dockerfile. Is this an alias for something? I would be inclined to use something like php /var/runtime/bootstrap, but I'd rather understand things, rather than guessing.
I believe I might be able to use Lambda RIE to test this locally, but I wonder if that would tell me what I already know - I need to fix the CMD.
For what it's worth, I can't see how the index.php file is triggered in the lambda either. How does that get invoked?
Update
I am wondering if the parent image in the example (public.ecr.aws/lambda/provided) has an ENTRYPOINT that would shed some light on the apparently confusing CMD. I wonder if I will investigate that next.
Update 2
The ponderance that I might have to use the Amazon Linux image parent was a false steer - this official resource shows the use of standard Python and Node images.
I decided to try repairing the main Docker command:
CMD ["php", "/var/runtime/bootstrap"]
However it doesn't like that:
START RequestId: d95a29d3-6764-4bae-9976-09830c1c17af Version: $LATEST
IMAGE Launch error: fork/exec /usr/local/bin/docker-php-entrypoint: permission denied Entrypoint: [docker-php-entrypoint] Cmd: [php,/var/runtime/bootstrap] WorkingDir: [/root]
IMAGE Launch error: fork/exec /usr/local/bin/docker-php-entrypoint: permission denied Entrypoint: [docker-php-entrypoint] Cmd: [php,/var/runtime/bootstrap] WorkingDir: [/root]
END RequestId: d95a29d3-6764-4bae-9976-09830c1c17af
REPORT RequestId: d95a29d3-6764-4bae-9976-09830c1c17af Duration: 19.88 ms Billed Duration: 20 ms Memory Size: 128 MB Max Memory Used: 3 MB
RequestId: d95a29d3-6764-4bae-9976-09830c1c17af Error: fork/exec /usr/local/bin/docker-php-entrypoint: permission denied
Runtime.InvalidEntrypoint
Update 3
No matter what I do, I seem to run into problems with entrypoints. I've even tried a runtime script to chmod +x on the various binaries it doesn't like, but of course if I try to kick that off in the ENTRYPOINT, the container believes that /bin/sh cannot be executed. This is getting rather silly - containers are just not behaving correctly in the Lambda environment.
Update 4
I have now tried to move away from Alpine, in case a more standard OS will work correctly. No joy - I get the same. I'm now at the random-trying things point, and this is rather slow going, given that the build-push-install loop is cumbersome.
This question looks promising, but putting the bootstrap file in /var/task seems to go directly against the example I am working from.
This problem was tricksy because there were two major interlocking problems - a seemingly excessive permissions requirement, and what struck me as a non-standard use of the ENTRYPOINT/CMD systems.
Working solution
The Dockerfile that works is as follows:
# Demo of a PHP-based lambda
#
# See example:
# https://github.com/aws-samples/php-examples-for-aws-lambda/blob/master/0.7-PHP-Lambda-functions-with-Docker-container-images/Dockerfile
FROM php:8.0-cli-alpine
WORKDIR /root
# Install Composer
COPY bin bin
RUN sh /root/bin/install-composer.sh
RUN php /root/composer.phar --version
# Install Composer deps
COPY composer.json composer.lock /root/
# Move deps to /opt, /root has significant permission issues
RUN php /root/composer.phar install && \
mv /root/vendor /opt/vendor
# Install runtimes
COPY runtime/bootstrap /var/runtime/
COPY src/index.php /var/task/
RUN chmod 777 /usr/local/bin/php /var/task/* /var/runtime/*
# The entrypoint seems to be the main handler
# and the CMD specifies what kind of event to process
WORKDIR /var/task
ENTRYPOINT ["/var/runtime/bootstrap"]
CMD ["index"]
So, that resolves one of my nagging questions about Amazon Linux - it is not required. Note that although I installed Composer dependencies in /root, they could not stay there - even 777 perms on them seemed to be insufficient.
As you can see I used 777 permissions on things in /var. 755 might work, maybe even 750 would work - but the key here is that Amazon appears to be a user that is not the build (root) user. That tripped me up a lot.
Now the ENTRYPOINT is used to run the bootstrap script, which appears to be doing general mediation between events on the AWS side and "use cases" in /var/tasks. The normal purpose of a Docker entrypoint is as a command wrapper to CMD, so to use CMD as a "default lambda type" seems to significantly violate the principle of least surprise. I would have thought the lambda type would be defined by the incoming event, not by any lambda-side setting.
Testing
To test this lambda I use this event in the Lambda UI:
{
"queryStringParameters": { "name": "halfer" }
}
And the demo code will respond with:
{
"statusCode": 200,
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Allow-Methods": "OPTIONS,POST"
},
"body": "Hello, halfer"
}
Suffice it to say this feels rather brittle. Admittedly the demo code is not production quality, but even so, I suspect this would need a pipeline to do a real AWS Lambda test prior to merging down or deployment.
Performance
Here is why lambdas are tempting, especially for infrequent calls such as crons - they are instantiated quickly and die quickly, leaving no running infra. In one of my demo calls I have:
Init duration 188.75 ms
Duration 39.45 ms
Billed duration 229 ms
Deeper understanding
Having worked with the pieces I think I can now explain them rather better, and what I thought of as unusual architectural choices may actually have some purpose. I fear however this design ideology is not sufficiently documented, so engineers working with Docker-based AWS Lambdas have to spend additional time figuring the pieces out.
Consider the processing loop in the demo runtime:
// This is the request processing loop. Barring unrecoverable failure, this loop runs until the environment shuts down.
do {
// Ask the runtime API for a request to handle.
$request = getNextRequest();
// Obtain the function name from the _HANDLER environment variable and ensure the function's code is available.
$handlerFunction = $_ENV['_HANDLER'];
require_once $_ENV['LAMBDA_TASK_ROOT'] . '/' . $handlerFunction . '.php';
// Execute the desired function and obtain the response.
$response = $handlerFunction($request['payload']);
// Submit the response back to the runtime API.
sendResponse($request['invocationId'], $response);
} while (true);
This picks up $_ENV['_HANDLER'] from the Lambda environment, and AWS derives that from the CMD of the image. Now, in PHP the env vars in $_ENV are static for the duration of the process, so it is perhaps a slightly odd choice to read this in a loop and include the file in a loop - it would have been better to do this in an initialisation phase, returning a clean error if the include isn't found.
However, here's the likely purpose of this system: AWS Lambdas let users customise the CMD in the web dashboard. So in an example enterprise let's say that there's three lambdas - one for responding to a web event, one for a scheduler, and one for responding to SNS topics. The handlers for each of these could be added to the same image, allowing the three lambdas to share an image - all they need to do is to supply a CMD override, and each one will load and use the right handler.

`lando artisan` command returns a weird error

If you've worked with Laravel and Lando together, you probably know that Lando gives you its own artisan shortcut. So instead of having to run lando php artisan ..., you can run lando artisan ....
However, when I do that, I get this error:
Could not open input file: /app/./../artisan
This forces me to have to run lando php artisan to run any artisan commands, and that does work fine. So far, this is all that's going wrong with my project in Lando. Everything else is running smoothly.
Here's what my lando config looks like:
name: laravel-project
recipe: laravel
config:
php: '7.4'
composer_version: '2.0.12'
database: mysql:8.0
services:
appserver:
webroot: public
xdebug: true
config:
php: .vscode/php.ini
node:
type: node:14
tooling:
node:
service: node
yarn:
service: node
Also, this does look a bit different from Lando's sample config on their website. This is because I was trying to configure xdebug according to their "Using Lando with VSCode" instructions (see Lando rc.2+ version).
Appreciate any help figuring this weird issue out. It's not debilitating, but it does get in the way when I forget the workaround.
Other notes:
"webroot" is set to "public" because that's where the public-facing directory is for a Laravel app. The example Lando config for Laravel has this part wrong and it causes the project root to be visible to the browser.
I got it working. I moved the webroot key back under the top-level config. Not sure what the difference is, but as long as it works... I guess the only thing I really need to specify in the appserver service is the Xdebug settings.
name: laravel-project
recipe: laravel
config:
php: '7.4'
composer_version: '2.0.12'
webroot: public
database: mysql:8.0
services:
appserver:
xdebug: true
config:
php: .vscode/php.ini
node:
type: node:14
tooling:
node:
service: node
yarn:
service: node

Can not run in DEV environment

I write you because I have a problem to run my project Symfony 4 DEV environment. Indeed, I have the impression that this one does not turn correctly because:
when I make a modification it is not visible immediately and I usually have to empty the caches to see them
the profiler and the associated "black bar" do not appear and return a 404 (I have the body tags in my base.htm.twig)
he does not see "immediately" the roads that I created
I installed the profiler via the following command composer require profiler --dev and I am in web server (directly on my NDD and my server).
I also have the variable APP_ENV in dev and it shows me well "dev" when I display it directly in a twig via {{app.environment}}
I hope that my explanations are clear enough and that you will be able to help me. thank you in advance
ps: sorry for my English, but I'm on Google Translate ;)
EDIT : I found the solution with the help of someone on Symfony slack ... I did not install the apache-pack bundle which created a .htaccess file in the public folder and manages the rewrites of url ... that's why my roads were not found.
For my defense, I did not see this bundle anywhere in the documentation
The first you have to install symfony/dotenv (dotenv)
In the .env follow this:
APP_ENV=dev
If you have not install symfony/dotenv
composer require symfony/dotenv
You can read about this here https://symfony.com/doc/current/components/dotenv.html
Also you have to follow config/packages/dev/web_profiler.yaml:
web_profiler:
toolbar: true
intercept_redirects: false
framework:
profiler: { only_exceptions: false }
It's not mandatory added APP_ENV=dev to your .env.
In Symfony 4 you can see in public/index.php this
if (!isset($_SERVER['APP_ENV'])) {
if (!class_exists(Dotenv::class)) {
throw new \RuntimeException('APP_ENV environment variable is not defined. You need to define environment variables for configuration or add "symfony/dotenv" as a Composer dependency to load variables from a .env file.');
}
(new Dotenv())->load(__DIR__.'/../.env');
}
$env = $_SERVER['APP_ENV'] ?? 'dev';
So if you APP_ENV is empty also you environment use is dev, but it's better use APP_ENV in .env

Laravel looking for path on my localhost instead of deployed server

I have Laravel installed on my localhost. And when I try to deploy it to the server, it throws an error: View [frontend.layouts.login] not found.
And I can see that it is looking at my local file path when on my machine aka:
/Applications/MAMP/htdocs/personal/project_name/resources/views
Instead of the server's file path.
If I try and copy the project outside of the personal folder (on my local machine), so make the file path:
/Applications/MAMP/htdocs/project_name/resources/views
It gives the same issue?
Is it something with caching the views?
The other error on the same page is:
file_put_contents(/Applications/MAMP/htdocs/personal/project_name/storage/framework/sessions/7a0aaa6c977031111312b785c7b7e22a659b6a36): failed to open stream: No such file or directory
And again, the server has nothing to do with my local machine.
What could be going on?
This issue is due to the Laravel Configuration Caching.I suggest you
Remove the configuration cache file
Flush the application cache
Create a cache file for faster configuration loading
To do this, run the following Artisan commands on your command line
php artisan config:clear
php artisan cache:clear
php artisan config:cache
Where you don't have access to the command line on your server, you can programmatically execute commands like this:
Route::get('/clear-cache', function() {
$exitCode = Artisan::call('config:clear');
$exitCode = Artisan::call('cache:clear');
$exitCode = Artisan::call('config:cache');
return 'DONE'; //Return anything
});
I hope this is helpful.
I think this might fix it
Go to config/app.php
and change the url to your production url
'url' => 'http://localhost',
I had the same issue so i tried many things including all the solutions in this question, but it didn't work.
What worked for me is that i just deleted this file bootstrap/cache/config.php and it worked.

Laravel BrowserSync without proxy

I'm trying to use Elixir BrowserSync, one of the newest features of Laravel.
I added it to the gulp file
elixir(function(mix) {
mix.sass('app.scss')
.browserSync();
});
when I run "gulp watch" it output this message
[20:49:20] Using gulpfile ~/Desktop/laravel/gulpfile.js
[20:49:20] Starting 'watch'...
[20:49:20] Finished 'watch' after 11 ms
[BS] Proxying: http://homestead.app
[BS] Access URLs:
----------------------------------
Local: http://localhost:3000
External: http://10.9.0.48:3000
Automatically a browser is launched with the url http://localhost:3000 but nothing loads.
I think the problem is related to this line:
[BS] Proxying: http://homestead.app
You can if you use BrowserSyncs server.
mix.browserSync({
proxy: false,
server: {
baseDir: './'
}
});
Are you running multiple homestead sites? It looks like it defaults to proxying through homestead.app if you do not include a proxy setting. If you don't host your local on homestead.app it won't find it.
Try
.browserSync({ proxy: 'domain.app' });
Where domain.app is what you are serving the site with.
The direct answer to your question - it is not possible to not proxy the .browserSync. Long side-answer - you can still use elixir's implementation of browserSync in gulp, but you must have a separate PHP server to interpret the files.
Edit: I saw a way to not proxy by providing the script in the pages manually (by not giving any arguments in the .browserSync() call, but don't remember where and how to do it exactly.
The reason is that browserSync requests all the data from the server for you, injects a little javascript listener and displays everything else:
<script type='text/javascript' id="__bs_script__">//<![CDATA[document.write("<script async src='/browser-sync/browser-sync-client.2.9.11.js'><\/script>".replace("HOST", location.hostname));//]]></script>
One way is to php artisan serve --host=0.0.0.0 in a separate terminal to start up the server and then use the .browserSync({proxy: 'localhost:8000'}). It all works - the BrowserSync UI and all the calls to refresh the pages.
Note: I could not connect to artisan serve without the --host=0.0.0.0.
For those wanting an all automated solution via gulp, here it is:
Use the gulp packages gulp-connect-php and laravel-elixir-browsersync2. The first starts up the php artisan serve and the other connects it to browserSync.
Install the packages:
npm install laravel-elixir-browsersync2 --save-dev
npm install gulp-connect-php --save-dev
Add the required lines to your gulpfile.js:
Code:
var elixir = require('laravel-elixir'),
gulp = require('gulp');
var connectPHP = require('gulp-connect-php');
var BrowserSync = require('laravel-elixir-browsersync2');
elixir(function(mix) {
mix.sass('app.scss');
});
elixir(function(mix) {
connectPHP.server({
base: './public',
hostname: '0.0.0.0',
port: 8000
});
BrowserSync.init();
mix.BrowserSync(
{
proxy: 'localhost:8000',
logPrefix : "Laravel Eixir BrowserSync",
logConnections : false,
reloadOnRestart : false,
notify : false
});
});
Then - simply gulp.
Disclaimer: This might not work with the gulp watch, but there might be people with the answer to that.
There is also a line PHP server not started. Retrying... before the [Laravel Eixir BrowserSync] Proxying: http://localhost:8000. It belongs to gulp-connect-php when trying to check if the server is running.
I found other solution on laracast for Bloomanity and it works with me like a charm!
$ php artisan serve --host=0
and then in your gulp add:
mix.browserSync({proxy: 'localhost:8000'});

Categories