I've built an SPA with Laravel, Vue js, Vuex and Laravel Passport for authentication.
I have a vuex store file that contains the apiURL and serverPath that I use throughout my application via services, where I make my axios requests.
store.js:
import Vue from 'vue';
import Vuex from 'vuex';
import * as auth from './services/auth_service.js';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
apiURL: 'http://highrjobsadminlte.test/api',
serverPath: 'http://highrjobsadminlte.test',
profile: {},
},
mutations: {
authenticate(state, payload) {
state.isLoggedIn = auth.isLoggedIn();
if (state.isLoggedIn) {
state.profile = payload;
} else {
state.profile = {};
}
}
},
actions: {
authenticate(context, payload) {
context.commit('authenticate', payload)
}
}
});
As you can see in the apiURL and serverPath variables, I'm developing on my localhost using this domain: http://highrjobsadminlte.test
After deploying my application to GoDaddy, I changed these variables to my actual domain: https://highrjobs.com
Now I'm getting this error:
app.js:26402 Mixed Content: The page at 'https://highrjobs.com/candidate/search' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://highrjobsadminlte.test/api/candidate/search'. This request has been blocked; the content must be served over HTTPS.
When I click on the app.js file, I can see that it still has the store.js code with the local domain in the apiURL and serverPath variables, But they are changed in the files on the Server 1000%.
I thought it's a caching issue so I ran these commands:
php artisan route:cache
php artisan cache:clear
php artisan config:cache
and it doesn't fix the issue. How can I fix this?
Mixed content: This request has been blocked
this error mostly get because
you are using https://highrjobs.com domain which is https protocol and u are using some url inside your application which is not https
apiURL: 'http://highrjobsadminlte.test/api',
serverPath: 'http://highrjobsadminlte.test',
like this u need to move in to https
in this error
app.js:26402 Mixed Content: The page at 'https://highrjobs.com/candidate/search' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://highrjobsadminlte.test/api/candidate/search'. This request has been blocked; the content must be served over HTTPS.
you can clearly see server try to serve https://highrjobs.com/candidate/search this secure url this unsecured api http://highrjobsadminlte.test/api/candidate/search
so fix this u need to use https to your api url as well
hope i explained well
and your code should be
apiURL: 'http://highrjobsadminlte.test/api' to apiURL: 'https://highrjobs.com/api',
Thank you
Sorry, I forgot to run npm run production before deploying. So my app.js file still had the old URL's.
Related
I'm making a website using NuxtJS for the front-end, and Laravel for the backend.
I need to have some data available on every page, so I fetch it using the nuxtServerInit function like so:
async nuxtServerInit({ commit }, { $axios }) {
const items= await $axios.$get('items')
commit('saveItems', items)
}
This works fine when pointing to my Laravel app that's already online, but not when I'm running it on my local machine. I get an "get addrinfo ENOTFOUND 3213" error.
My .env file contains the baseURL for axios, so local would be:
API_URL=http://127.0.0.1:8000/v1/
I tried many things but to no avail. It works when using the live backend, and there's no problem with the API_URL as it works on every other function/page apart from the nuxtServerInit one. I tried:
Using nuxt/dotenv as well as their new runtimeConfig settings to configure Axios' base URL in nuxt.config.js
Changing the port on which my backend runs
Changing the port on which my frontend runs
Adding a custom URl for my local backend (like devlocal.com pointing to localhost:8000)
But nothing works. My /etc/host file also correctly contains 127.0.0.1 as I saw it was a solution for a lot of ENOTFOUND errors on local.
I also tried changing the API_URL in my .env file to
API_URL=localhost:8000/v1/
But then I get "ENOTFOUND 8000" instead, or whichever the port I set my Laravel server to.
Please help!
Edit:
After toggling debug on Axios on dev, I found the host name is wrong in the request, which in turns make the URL incorrect:
reusedSocket: false,
host: '3213',
protocol: 'http:',
_redirectable: [Circular *1],
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype]
},
_currentUrl: 'http://3213/http://localhost:8000/v1/items',
I don't know where the "3213" comes from. I tried setting default host/hostnames/port values to Axios in nuxt.config.js, but no luck.
Solved it randomly. I had a proxy variable setup in my environment variables (Win 10) called "http_proxy". Deleted it, and no more problem.
I am starting a new project, Nuxt.js for the frontend and Laravel for the backend.
How can I connect the two?
I have installed a new Nuxt project using create-nuxt-app, and a new laravel project.
As far as I have searched, I figured I need some kind of environment variables.
In my nuxt project, I have added the dotenv package and placed a new .env file in the root of the nuxt project.
And added CORS to my laravel project, as I have been getting an error.
The variables inside are indeed accessible from the project, and im using them
like this:
APP_NAME=TestProjectName
API_URL=http://127.0.0.1:8000
And accessing it like this:
process.env.APP_NAME etc'
To make HTTP calls, I am using the official Axios module of nuxt.js, and to test it i used it in one of the components that came by default.
The backend:
Route::get('/', function () {
return "Hello from Laravel API";
});
and from inside the component:
console.log(process.env.API_URL)//Gives 127.0.0.1:8000
//But this gives undefined
this.$axios.$get(process.env.API_URL).then((response) => {
console.log(response);
});
}
What am I doing wrong here?
I have tried to describe my setup and problem as best as I can. If I overlooked something, please tell me and I will update my question. Thanks.
Taking for granted that visiting https://127.0.0.1:8000/ in your browser you get the expected response, lets see what might be wrong in the front end:
First you should make sure that axios module is initialized correctly. Your nuxt.config.js file should include the following
//inclusion of module
modules: [
'#nuxtjs/axios',
<other modules>,
],
//configuration of module
axios: {
baseURL: process.env.API_URL,
},
Keep in mind that depending on the component's lifecycle, your axios request may be occurring in the client side (after server side rendering), where the address 127.0.0.1 might be invalid. I would suggest that you avoid using 127.0.0.1 or localhost when defining api_uris, and prefer using your local network ip for local testing.
After configuring the axios module as above, you can make requests in your components using just relative api uris:
this.$axios.$get('/').then(response => {
console.log(response)
}).catch(err => {
console.error(err)
})
While testing if this works it is very helpful to open your browser's dev tools > network tab and check the state of the request. If you still don't get the response, the odds are that you'll have more info either from the catch section, or the request status from the dev tools.
Keep us updated!
Nuxt has a routing file stucture to make it easy to set up server side rendering but also to help with maintainability too. This can cause Laravel and Nuxt to fight over the routing, you will need to configure this to get it working correctly.
I'd suggest you use Laravel-Nuxt as a lot of these small problems are solved for you.
https://github.com/cretueusebiu/laravel-nuxt
My server uses SSL and thus all my routes/urls use https. I recently discovered a bug in Laravel 5.7 which was exposed when trying to use Email Verification, which does not work on a server with https. I wont go into the specifics of that problem as I have another question for that. I want to keep this simple.
I have the following settings in my .env file:
APP_USE_HTTPS=true
APP_URL=https://www.example.com
APP_ENV=production
And I have the following in the boot() method of the AppServiceProvider
if (env('APP_USE_HTTPS')) {
Log::info('AppServiceProvider: forcing URLs to use https');
URL::forceScheme('https');
}
And it may be overkill but to try to resolve the issue I also put the following code at the top of my web.php routes file"
if (env('APP_USE_HTTPS')) {
Log::info('Routes: forcing URLs to use https');
URL::forceScheme('https');
}
Route::get('/', 'PublicController#getHome');
Route::get('home', 'PublicController#getHome');
Then in my PublicController.getHome() method I put this code:
public function getHome()
{
$currentPath= Request::fullUrl();
Log::info($currentPath);
return view('public.home');
}
Now I go to my browser and enter this in the address bar:
https://www.example.com
And I get this in my log file:
AppServiceProvider: forcing URLs to use https
Routes: forcing URLs to use https
http://www.example.com
So as you can see from the last log message the fact that laravel always uses http instead of https is beginning to create issues. Starting with signed routes. I am trying to use the built-in Email Verification but the signature is being generated using https route and the email sent to user does have https in the url for going back to the same server. However the validation for the route is using http (even though https was used) so it generates a different signature and thus all verifications links fail with a 403 error.
Is there anything I am missing? I can't seem to find code that shows me how Laravel knows to use https or http or is it just hard coded for http?
Thanks for any help you can give me.
*** Update to show problem with Shaielndra Gupta answer ****
After implementing the middleware below is the code I used but as you will see the core problem exists in ALL methods dealing with url. So for example:
$request->secure()
returns false even when https was used. Then by calling:
redirect()->secure($request->getRequestUri());
does no good because that will cause the route to loop back into this method again which still returns false for secure(), basically creating an infinite loop (or infinite too many redirects)
class ForceHttpsProtocol {
public function handle($request, Closure $next) {
Log::info('request uri: '.$request->fullUrl());
Log::info('secure: '.($request->secure() ? 'yes' : 'no'));
if (!$request->secure() && env('APP_USE_HTTPS')) {
return redirect()->secure($request->getRequestUri());
}
return $next($request);
}
}
The log from the above code will produce the following when you make 1 attempt to go to any page even when using https://www.example.com
request uri: http://www.example.com
secure: no
request uri: http://www.example.com
secure: no
request uri: http://www.example.com
secure: no
request uri: http://www.example.com
secure: no
< over and over till page times out >
After much research I finally discovered what the issue is.
My live server is installed on an Amazon EC2 server which is behind a Load Balancer.
The load balancer is receiving the (https) request and handling all the SSL requirements and then forwarding the request to my website as http.
To fix this issue I had to install the fideloper/TrustedProxy package. This package allows my site to trust the proxy and get the valid headers for the request so it now knows the request was actually sent using https.
Laravel wrote an article which describes my condition exactly.
https://laravel-news.com/trusted-proxy
This is the package I installed:
https://github.com/fideloper/TrustedProxy
change in your config/session.php
'http_only' => true,
change it to
'http_only' => false,
or make a middlewere HttpsProtocol.php
namespace MyApp\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\App;
class HttpsProtocol {
public function handle($request, Closure $next)
{
if (!$request->secure() && App::environment() === 'production')
{
return redirect()->secure($request->getRequestUri());
}
return $next($request);
}
}
Then, apply this middleware to every request adding setting the rule at Kernel.php file in protected $routeMiddleware array,
'https'=>App\Http\Middleware\HttpsProtocol::class
change This
APP_USE_HTTPS=true
APP_URL=https://www.example.com
to this
APP_URL=http://www.example.com
APP_USE_HTTPS=false
Because Laravel uses APP_URL to generate urls.
Many laravel/vue tutorials use ajax calls to get the data. It seems that the SPA is completely isolated from Laravel. I.e. Laravel is just a data API and the vue app could also simply be hosted on a third party external server (e.g. AWS S3). Is this the recommended way, or should I rather use Laravel for Routing and have separate views that implement individual components and already included data instead of using a SPA?
For an SPA, I would recommend just going with the standard setup, which is Laravel on the webserver and Vue in the browser. To do this, install Laravel and Vue. AJAX communications from the browser to the server are accomplished with the Axios library which comes with Vue. Here is how to install Laravel and Vue router:
composer require laravel/ui
php artisan ui vue
npm install && npm run dev
npm install vue-router
npm run watch
From within a Vue component, using Axios to communicate with the server looks like the following. Also, in the following, the endpoint is defined in the Laravel > Routes > web.php:
methods: {
fetchMessages() {
let endpoint = `/channels/${this.activeChannel}/messages`;
axios.get(endpoint).then(resp => {
this.messages = resp.data.messages;
});
},
A Vue router is declared in the main js file. For instance, in app.js.
Here is what a Vue router looks like, and additional url paths would be added under "routes":
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const router = new VueRouter({
base: '/',
mode: 'history',
history: true,
routes: [
{
path: '/',
name: 'home',
component: PostComponent
},
],
});
I'm runing reactjs in a localhosted server using webpack. I need to make an ajax call from my reactjs application (client side) to my backend, which is also a local hosted server but using a different port. When i make a request to my backend from postman, there is no problem. But when i try to do the same from my react js application, i got this error in my console :
XMLHttpRequest cannot load http://localhost:8888/api. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
Uncaught (in promise) Error: Network Error
at createError (createError.js:15)
at XMLHttpRequest.handleError (xhr.js:87)
It's seems to be a C.O.R.S issue. After several hours of research on internet i can't find a solution.
There is my code
react :
handleClick(){
console.log('focused')
axios.get('http://localhost:8888/api').then(function(result){
console.log(result)
})
}
webpack config
devServer: {
contentBase: 'http://localhost',
port: 8888,
// Send API requests on localhost to API server get around CORS.
proxy: {
'/api': {
target: {
host: "localhost",
protocol: 'http:',
port: 3000
}
}
}
}
Thanks for helping
Try making your call without the host like this:
handleClick(){
console.log('focused')
axios.get('/api').then(function(result){
console.log(result)
})
}