Using PHP scripts in Vue - javascript

I have Vue app that has to use some PHP scripts. If I place them on server everything works fine and I am able to make Axios request like:
this.$http
.post("http://my-domain.com/scripts/news.php", {
action: "getAll"
})
Still, I would like to have those scripts in my local development environment and use them like this:
this.$http
.post("/scripts/news.php", {
action: "getAll"
})
with scripts placed in public/scripts. When tried with PHP dev server or Apache I could only use them when requesting http://localhost/scripts/news.php and proxing PHP server with vue.config.js, but it is not useful since I would need to change that when switching to production.
How to configrue it properly?

try setting up the base url of axios.
import axios from 'axios'
window.axios.defaults.headers.common = {'X-Requested-With': 'XMLHttpRequest'}
window.axios.defaults.baseURL = (process.env.NODE_ENV !== 'production') ? 'http://my-domain.com/' : ''

Related

Nuxt.Js axios not using baseURL despite it being set correctly

I want to call an API in asyncData()
async asyncData({ $axios, params, store }) {
let itemUUID = params.item;
let item = await $axios.get("/item/" + itemUUID);
return {item};
}
Problem: Axios is still making the request on http://localhost:3000
if I do a console.log($axios.defaults.baseURL) the correct baseURL of my API is printed.
This also works if I use my store action & make the call by using this.$axios
I am using #nuxtjs/axios 5.13.1 with Nuxt 2.15.6 in SSR mode and configured it with the correct baseURL in the nuxt.config.js
Interestingly, if I edit my page content and a hot module reload is triggered, the correct URL is used. Maybe the question should be if Axios is triggered in the right time, on the server?
Edit: I checked the request that was made on HMR and this was triggered in the client.js.
If I call my store inside the created() hook the request gets executed successfully.
My nuxt.config.js:
publicRuntimeConfig: {
axios: {
baseURL: process.env.EXPRESS_SERVER_URL
}
},
privateRuntimeConfig: {
axios: {
baseURL: process.env.EXPRESS_SERVER_URL,
}
},
I'm not sure what is the NODE_TLS_REJECT_UNAUTHORIZED=0 thing doing but your frontend configuration (Nuxt) is working well so far.
Sorry if I cannot help on the Express part.
Maybe try to setup HTTPS locally on Nuxt: How to run NUXT (npm run dev) with HTTPS in localhost?
TLDR; This was not related at all - I forgot to set the auth token for my backend. At the time of axios init it's not present. $axios object doesn't have auth - backend fails.
On page load the nuxt function nuxtServerInit() is used to get the auth token out of the acces_token cookie.
I am using a plugin to initialize Axios - with the token from the store.
But of couse the token is not present at the time axios is initialized as nuxtServerInit is called after plugin init.
In my axios.js plugin I changed:
export default function({ app, error: nuxtError, store }) {
const token = const token = store.state.user.token;
app.$axios.setToken(token, "Bearer");
}
to;
export default function({ app, error: nuxtError, store }) {
const token = app.$cookies.get("access_token");
app.$axios.setToken(token, "Bearer");
}
Now the token is present & used for every request happening server-side.

Import external JS into Angular 8

I am writing application in Angular 8 (8.0.3) and I need to import external JS file which will hold a URL reference for API that can and will change. The problem I am facing is that changes I do into this file after I have compiled Angular app (with ng build --prod), changes are not being picked up inside Angular, but it keeps the data as it was when the app was built.
This is the external JS file:
export function apiUrl() {
return 'http://www.localhost.local/api/v1/';
}
The apiUrl() does return proper value, but if I change it, the updated value is not reflected inside Angular app.
I also created .d.ts. file:
export declare function apiUrl();
Imported the external JS file into index.html:
<script type="module" src="assets/js/api_url.js"></script>
Used it in angular service:
import {apiUrl} from '../../assets/js/api_url';
export class ApiService {
private api_url: string = apiUrl();
constructor(...) {
console.log(apiUrl());
}
}
I did NOT import this file in angular.json and even if I do, nothing changes.
So, how to create and then import an external JS file that after it changes, the Angular app does pick up it changes?
EDIT:
Do note that I do not need a live app reload when this file changes, but I need for the file to be loaded from server each time the Angular app starts.
EDIT 2:
To explain why I need this. The Angular app will be used on internal network to which I do not have access to. The client currently does not know the API URL and even if he would, it can change at any moment. That's the reason why I need this to work.
In that case you should use environments
You can find them in src/environments directory.
For local development you have environment.ts file, for production environment.prod.ts
Example environment.ts:
export const environment = {
production: false,
apiUrl: 'http://www.localhost.local/api/v1/'
};
environment.prod.ts:
export const environment = {
production: true,
apiUrl: 'http://www.producitonurl.com/api/v1/'
};
To use this apiUrl value you need to import environment file in typescript file like this:
You need to import environment.ts not any other environment file, because angular is replacing it while building application
import {environment} from '../environments/environment';
#Injectable({
providedIn: 'root'
})
export class MyApiService {
apiUrl = environment.apiUrl;
}
But in case you want to use method from <script type="module" src="assets/js/api_url.js"></script>, just use window object like this:
private api_url: string = (window as any).apiUrl();

How to change the dynamic baseUrl Laravel + Vue.js?

How do I set the baseUrl so if I switch from server to server on the frontend (Vue.js), it changes dynamically to baseUrl?
I show my code axios-auth.js code:
import axios from 'axios'
const instance = axios.create({
baseURL: 'http://mvp.test/api/public/api/'
// baseURL: 'http://127.0.0.1:8000/api/' for testing localhost
});
and my .env file which have standard code for laravel.
Taken from the official mix documentation, you can use an environment variable by creating a key in your .env prefixed with MIX_:
MIX_BASE_URL=http://mvp.test/api/public/api/
And run php artisan config:clear to be sure the new config is set.
Then, in javascript you can access the variable inside the process.env object:
process.env.MIX_BASE_URL
So you can simply use it like this:
const instance = axios.create({
baseURL: process.env.MIX_BASE_URL
});

Fetch local JSON file from public folder ReactJS

I have a problem since two days; I want read a local JSON from my public folder on my React application created with react-app.
This is my project structure:
public
data
mato.json (my .JSON file)
src
components
App.js
Why I put my file in public folder? If I build my project with file in src folder, my file will be include in the generated main.js by the command yarn build.
I want modify my json file without always rebuild my app.
So I can't use code like:
import Data from './mato.json'
…or:
export default { 'mydata' : 'content of mato.json'}
import data from 'mydata';
I tried to fetch my .json file but "file scheme" isn't friend with fetch() & chrome..
(Chrome error: “index.js:6 Fetch API cannot load file:///D:/projects/data/mato.json. URL scheme "file" is not supported.”)
This is my code for fetch:
fetch(`${process.env.PUBLIC_URL}/data/mato.json`)
.then((r) => r.json())
.then((data) =>{
ReactDOM.render(<App appData={JSON.stringify(data)}/>, document.getElementById('root'));
})
It's only works with Firefox. I also tried mode: 'cors' does not better.
And of course I don't have any server — it's a local project — so if someone knows how I can read my JSON file locally I will much appreciate.
I think your fetch argument is wrong. It should be
fetch('data/mato.json')
You also need to pass in some headers indicating the Content-Type and Accept as application/json to tell your client that you are trying to access and accept some JSON resource from a server.
const getData=()=>{
fetch('data/mato.json'
,{
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}
)
.then(function(response){
console.log(response)
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
}
useEffect(()=>{
getData()
},[])
As long as data files are placed in public folder, it should work in Chrome also as in my project.
So, fetch('data/mato.json') is enough for it.
give your JSON file name which is present in the public folder and store the data links
componentDidMount() {
fetch("./url.json")
.then((res) => res.json())
.then((data) => {
this.setState({ links: data });
console.log(this.state);
});
}
why using fetch? I think the speed is slow...
I think this solution would be better...
you can add this line into your index.html:
<script type="text/javascript" src="settings.js"></script>
then in settings.js you can do this:
window.globalTS= {
"site_url": "hi.com",
"home_url": "hello.com"
};
now in your components you can get to variables like this:
console.log(window.globalTS.site_url);
share and comment me your idea, thanks!

Using angular 2 http offline when loading JSON in local project folder

I have been trying loading a local json file present in my project folder of Angular 2 using http get method. Look at the following example code snippet:
private _productURL = 'api/products/products.json';
getProducts(): Observable<any> {
return this._http.get(this._productURL).map((response : Response) => <IProduct[]> response.json())
.do(data =>console.log(JSON.stringify(data))).catch(this.handleError);
}
Now when I'm trying to load it with internet connected, it's working. But when I'm turing on the offline checkbox from the browser developer options(https://developers.google.com/web/tools/chrome-devtools/network-performance/reference#offline), the json stops loading again. It starts showing me error in console about No internet connection and doesn't load anything.
Is there any other way to do this? or using http get..how to do it?
You can import a json file if you do as follows:
create a json-typings.d.ts file with:
declare module "*.json" {
const value: any;
export default value;
}
this is a wildcard module definition that allows us to import non javascript files in this case JSON files.
you should now be able to import json files to your project:
import * as products from "./products.json";

Categories