Laravel (Sail): Vite Dev Server not found (404) - php

I am currently switching from webpack to vite.
Current status is, that build commands (yarn production) works for js and css using vite.
However, using the dev server, I receive an 404 message telling me, that the files weren't found - what did I miss?
Below is my code:
vite.config.js
export default ({ command }) => ({
base: command === 'serve' ? '' : '/build/',
publicDir: 'fake_dir_so_nothing_gets_copied',
build: {
manifest: true,
outDir: 'public/build',
rollupOptions: {
input: 'resources/js/app.js',
},
},
server: {
strictPort: true,
port: 3000
},
resolve: {
alias: {
'#': '/js',
}
}
});
helpers.php
<?php
use Illuminate\Support\Facades\Http;
use Illuminate\Support\HtmlString;
function vite_assets(): HtmlString
{
$devServerIsRunning = false;
if (app()->environment('local')) {
try {
Http::get("http://localhost:3000");
$devServerIsRunning = true;
} catch (Exception) {
}
}
if ($devServerIsRunning) {
return new HtmlString(<<<HTML
<script type="module" src="http://localhost:3000/#vite/client"></script>
<script type="module" src="http://localhost:3000/resources/js/app.js"></script>
HTML);
}
$manifest = json_decode(file_get_contents(
public_path('build/manifest.json')
), true);
return new HtmlString(<<<HTML
<script type="module" src="/build/{$manifest['resources/js/app.js']['file']}"></script>
<link rel="stylesheet" href="/build/{$manifest['resources/js/app.js']['css'][0]}">
HTML);
}
so I can finally embed {{ vite_assets() }} inside my blade layout

I recommend you to use: https://laravel-vite.dev/ when passing from webpack to vite, it worked perfect for me and took me like less than an hour.

Related

Run php file in node

I have an application that I'm trying to migrate to a node server, but when it needs to query a file on my server, it always fails.
I managed to run the statics with Express, but when php makes a query it always returns an error similar to:
Cannot POST "/path-to-file/file.php"
The structure of the files is like this:
app
public
routes
index.php
statics
index.html
server.js
package.json
server.js:
const express = require('express');
const app = express();
app.listen(5000, () => console.log('Server is up and running'));
app.post('/', (req, res) => {
res.send('POST request to the homepage')
})
app.use(express.static('public'));
index.php :
<?php
$res = '<h1>Random Title'</h1>;
$echo $res;
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Socket Sender</title>
</head>
<body onload="getPage()">
<div id="table_container">
</div>
<script language=javascript>
function getPage(){
fetch('path/to/file', {
method: 'POST',
mode: 'cors',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(body),
})
.then((response) => response.text())
.then((data) => {
if(data){
console.log(data);
}
}
);
}
</script>
</body>
</html>
I would like help to know if it is possible to run these scripts in node or if I have to rewrite all of them
I'm new to node so if I said something absurd please ignore it

react native 403 permission error from php api on wamp server

react native error
import React, { Component } from 'react';
import { ActivityIndicator, FlatList, Text, View } from 'react-native';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
isLoading: true
};
}
async getMovies() {
try {
const response = await fetch('http://192.168.1.6:80/p4Lite/Sept2021/react_backend/index.php');
const json = await response.json();
this.setState({ data: json });
} catch (error) {
console.log(error);
} finally {
this.setState({ isLoading: false });
}
}
componentDidMount() {
this.getMovies();
}
render() {
const { data, isLoading } = this.state;
return (
<View style={{ flex: 1, padding: 24 }}>
{isLoading ? <ActivityIndicator/> : (
<FlatList
data={data}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => (
<Text>{item.name}, {item.email}</Text>
)}
/>
)}
</View>
);
}
};
Above is my app.js file code. It works fine on web but shows error on my android phone using expo go. I have tried various methods but till now is solution fond. I am working on localhost.
Try this on your API related folder
sudo chmod -R -f 777 /path/to/your/file/or/directory
the 403 error means that the request you made was forbidden. it is generally received when a required password is not entered.
Most likely, your API requires a password, and this was not provided by the code, the server code is miss-configured, or the server does not have the right permissions to display the result.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403
Some how it's working by changing:
Require local to Require all granted in httpd-vhosts.conf

how to use Directus with gatsby

How is it possible to use the Directus data in getsby.js
I've setup a Directus app, and added tables and data/columns but I have no clue how to use it in gatsby.js, I have build a template like this in jsx:
const path = require('path')
exports.createPages = ({ boundActionCreators, graphql }, { urlPrefix }) => {
const { createPage } = boundActionCreators
return new Promise((resolve, reject) => {
resolve(
graphql(
`
{
allDirectusPost {
edges {
node {
id
title
author
content
}
}
}
}
`
).then(result => {
if (result.errors) {
console.error('GraphQL query returned errors')
reject(result.errors)
}
result.data.allDirectusPost.edges.forEach(edge => {
try {
let node = edge.node
let path = `posts/${node.id}`
createPage({
path,
layout: 'index',
component: path.resolve('src/templates/post.jsx'),
context: {
post: node,
},
})
console.log(`Generated page '${path}'`)
}
catch (error) {
console.error(`Failed to generate page posts/'${path}': ${error}`)
}
})
})
)
})
}
and I have a homepage static site in gatsby.js like this
import React from 'react'
import Link from 'gatsby-link'
// import postsTemplate from '../templates/post.jsx'
const IndexPage = () => (
<div>
<h1>Hi people</h1>
<p>Welcome to your new Gatsby site.000</p>
<p>Now go build something great.</p>
<post />
<Link to="/page-2/">Go to page 2</Link>
</div>
)
export default IndexPage
how do I call the directus data in that gatsby file?
For each item in your Directus table, a new page will be created based off the src/templates/post.jsx component. This will be a completely separate set of pages to the IndexPage.
The steps to source pages from Directus is very similar to the steps to source pages from Markdown. I recommend you read https://www.gatsbyjs.org/docs/adding-markdown-pages/ one more time (though it looks like you did read it, since your gatsby-node.js code looks like it was borrowed from there). In posts.jsx, instead of querying markdownRemark(frontmatter: { path: { eq: $path } }) you want to query allDirectusPost(edges: { node: {id: {eq: $path } } }).

GET and POST issue in laravel chat using Pusher and Vue.js

I have a problem following this tutorial to implement a simple chat in Laravel using Pusher and Vue.js: link tutorial.
First of all my route in the navbar is this one:
http://localhost/youChat/public/
My web.php file contents the following routes:
Auth::routes();
Route::get('/', 'TweetController#index');
Route::get('tweets', 'TweetController#showTweets')->middleware('auth');
Route::post('tweets', 'TweetController#sentTweet')->middleware('auth');
My app.js file in assets/js where I make the request is this one:
const app = new Vue({
el: '#app',
data: {
tweets: []
},
created() {
this.showTweets();
Echo.private('chat')
.listen('TweetSentEvent', (e) => {
this.tweets.push({
tweet: e.tweet.tweet,
user: e.user
});
});
},
methods: {
showTweets() {
axios.get('/tweets').then(response => {
this.tweets = response.data;
});
},
addTweet(tweet) {
this.tweets.push(tweet);
axios.post('/tweets', qs.stringify(tweet)).then(response => {
console.log(response.data);
});
}
}
});
As you can see I send the request with Axios.
Everything seems looks fine but the GET and POST request are not working. The error in the console inspector shows this:
GET http://localhost/tweets 404 (Not Found)
Uncaught (in promise) Error: Request failed with status code 404
at createError (app.js:13931)
at settle (app.js:35401)
at XMLHttpRequest.handleLoad (app.js:13805)
GET https://stats.pusher.com/timeline/v2/jsonp/1session=Njg3NjQyNDY5NT....MjY1fV0%3D 0 ()
POST http://localhost/broadcasting/auth 404 (Not Found)
And when I try to make a POST:
POST http://localhost/tweets 404 (Not Found)
The get/post should go to this direction:
http://localhost/youChat/public/tweets
but I don't know what's happening. Any suggestion? I'm desperated :D.
Thanks in advance!
You are getting this error because you are using an absolute path.
So either you can store the Base url in a variable or you can use relative path
here is an example.
methods: {
showTweets() {
axios.get('tweets').then(response => {
this.tweets = response.data;
});
},
addTweet(tweet) {
this.tweets.push(tweet);
axios.post('tweets', qs.stringify(tweet)).then(response => {
console.log(response.data);
});
}
}
Remove the / before the URL or
save a
const URL = '{{url('/')}}'
methods: {
showTweets() {
axios.get(URL + '/tweets').then(response => {
this.tweets = response.data;
});
},
addTweet(tweet) {
this.tweets.push(tweet);
axios.post(URL + '/tweets', qs.stringify(tweet)).then(response => {
console.log(response.data);
});
}
}
Hope this helps

POST from vuejs to php script in same directory

I'm trying to post data from vue to php script which exists in the same folder.
when executing npm run dev my vue app start's on port 8080, while my Apache configuration uses port 80. what i want to do is to pass data from my vue app which "lives" in the address http://localhost:8080 to my script which i can access using the address http://localhost:80/project_name .
i tried this app as an example github.com/0x90kh4n ,and while the app works when i simply clone it, when adding it to my "real world" project where i use webpack,babel,npm etc. i cant access it since the app always send requests to localhost:8080 . tried changing the proxy table like this:
proxyTable: {
'/api' : 'http://localhost:80/project_name'
}
but it didn't work, here is my implementation of the code in my (single) vue instance
<script>
import Navigation from './components/partials/Navigation.vue'
export default {
name: 'app',
data () {
return{
name: '',
surname: '',
users: []
}
},
created: function() {
this.fetchData(); // Başlangıçta kayıtları al
},
methods: {
fetchData: function() {
this.$http.get('/api.php')
.then(function(response) {
if (response.body.status == 'ok') {
let users = this.users;
response.body.users.map(function(value, key) {
users.push({name: value.name, surname: value.surname});
});
}
})
.catch(function(error) {
console.log(error);
});
}
},
components: {
Navigation
}
}
in the endpoint there is this file, which i'm not including pieces of code from it here since i believe the problem is my vue part of the story...
Might be worth adding my /config/index.js export:
module.exports = {
build: {
env: require('./prod.env'),
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
productionSourceMap: true,
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
bundleAnalyzerReport: process.env.npm_config_report
},
dev: {
env: require('./dev.env'),
port: 8080,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api' : 'http://localhost:80/projedt_name'
},
cssSourceMap: false
}

Categories