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
Related
I'm trying to test and learn how fetch works so I want to send some data from javascript to a php file, my problem is that I can't retrieve the data (in the php file), only getting a null response.
I'm using POST but I have tried with GET with the same result
As a side note, in console the conection in network only appears after I press F5 , as I understand it, to work should be already when I open Test.php.
datosJS.js
let datos = {
method: "POST",
headers: {
"Content-type" : "application/json"
},
body: JSON.stringify({
username:"Jonathan",
email:"jonathan#gmail.com",
password:"123456"
})
}
fetch('Test.php',datos)
.then(resp => resp.text())
.then(resp =>{
console.log(resp);
})
Test.php
<script src="datosJS.js" type="text/javascript"></script> //I use this to call "datosJS.js" to receive the data here in Test.php
<?php
$body = json_decode(file_get_contents("php://input"), true);
var_dump($body);
?>
I understand PHP is on server side and JS on client side and both of them run in different times, nevertheless I'm having troubles to find the solution to this problem.
Thank you for your help !
** Edited a small change in fetch which now let me see the data in console
Well finally I managed to get the solution to this, explanation is below:
datosJS.js
window.onload = function() {
let datos = {
method: "POST",
headers: {
"Content-type" : "application/json"
},
body: JSON.stringify({
username:"Jonathan",
email:"jonathan#gmail.com",
password:"123456"
})
}
fetch('Test.php',datos)
.then(resp => resp.text())
.then(resp =>{
console.log(resp);
document.getElementById('results').innerHTML = resp;
//document.querySelector('#results').innerHTML = resp; // works as well as getElementById
})
}
Test.php
<script src="datosJS.js" type="text/javascript"></script>
<section class="Section" id="results" name="results">
<?php
$body = json_decode(file_get_contents("php://input"), true);
$nombre = $body['username'];
echo $nombre;
echo '</br>';
print_r($body);
?>
Below I will mark what was lacking in the original code:
In datosJS.js document.getElementById('results').innerHTML = resp; and wrap everything in window.onload = function() {}
In Test.php add the id="results" name="results" to a div, section or whatever to receive from the innerHTML.
I hope it helps someone in the future. Cheers
i have a problem with my NodeJS/MySQL-Events (from rodrigogs on Github) solution and hope someone here can help me.
Current setup looks like this:
MySQL Server <-> Socket.io with MySQL-Events listening for new Database Entrys (trigger on INSERT and UPDATE)
-> Axios GET Request from index.js to sync.php (different Server)
-> calling Method from class.php inside sync.php with data from that GET Request
No problems with Socket.IO clients. Just with to many GET Request at the same time from NodeJS/Socket Server -> Apache
If i get just a few new database entrys separately, everything works fine.
If i get a lot of new database entrys at almost the same time, some of them not running the Method from sync.php/class.php
index.js (Node/Socket Server with MySQL-Events Trigger)
const program = async () => {
const instance = new MySQLEvents(conn, {
startAtEnd: true,
excludedSchemas: {
mysql: true,
},
});
await instance.start();
const agent = new https.Agent({
rejectUnauthorized: false
});
instance.addTrigger({
name: 'INSERT',
expression: 'table.column',
statement: MySQLEvents.STATEMENTS.INSERT,
onEvent: (event) => {
console.log("New Entry in Database " + event)
const id = event.affectedRows[0].after.ID;
const status = event.affectedRows[0].after.STATUS;
if (status === 11) {
axios.get('https://serverurl.dev/sync.php', {
params: {
id: id,
status: status
},
withCredentials: true,
httpsAgent: agent,
auth: {
username: 'user',
password: 'pwd'
}
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
}
}
});
instance.on(MySQLEvents.EVENTS.CONNECTION_ERROR, console.error);
instance.on(MySQLEvents.EVENTS.ZONGJI_ERROR, console.error);
};
serverurl.dev/sync.php
<?php
if (!empty($_GET)){
$id = $_GET['id'];
$status = $_GET['status'];
$classname->method($id, $status);
}
serverurl.dev/class.php
public function method($id, $status)
{
// lots of things happen here
}
My guess is that the method in class.php isnt finished running while the next GET Requests are coming in and calling the method again to fast?
Any ideas how to solve this problem?
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.
I am having an issue where browsersync does not find/open my index.php file.
The relevant parts of my gulp file are as follows:
const browserSync = require("browser-sync").create();
const php = require('gulp-connect-php');
// Configure PHP server
gulp.task('php', function(){
php.server({base:'./', port:8010, keepalive:true});
});
// Inject php config into browserSync task
gulp.task('browserSync', function() {
browserSync.init({
proxy:'localhost:8000',
port: 8080,
baseDir: './',
open:true,
notify:false
});
});
// Watch files
function watchFiles() {
gulp.watch("./scss/**/*", css);
gulp.watch(["./js/**/*", "!./js/**/*.min.js"], js);
gulp.watch("./**/*.php", browserSync.reload);
gulp.watch("./**/*.html", browserSync.reload);
}
const watch = gulp.series(build, gulp.parallel(watchFiles, browserSync.reload));
// Export tasks
exports.watch = watch;
My console output when 'Gulp watch' is run looks like this:
The page never opens in the browser.
Any advice as to why it is getting hung up on browser-sync?
Also, browsersync works when run directly in the cmd with:
browser-sync start --proxy "localhost/BtcMiningContracts" --files "*.php, *.html, css/*.css, ./js/**/*"
thanks!
Many hours of searching have resulted in a working answer.
For anyone else experiencing the same issue, the updated code is below:
const browserSync = require("browser-sync");
const php = require('gulp-connect-php');
// Configure PHP server
gulp.task('connect-sync', function() {
php.server({}, function (){
browserSync({
proxy: '127.0.0.1:8000'
});
});
gulp.watch('**/*.php').on('change', function () {
browserSync.reload();
});
});
// Watch files
function watchFiles() {
gulp.watch("./scss/**/*", css);
gulp.watch(["./js/**/*", "!./js/**/*.min.js"], js);
gulp.watch("./**/*.php").on('change', function () {
browserSync.reload()});
}
This works with scss
hope it helps somebody out :)
I know there are several posts on SO and on many blogs explaining how to get the JSON data that was sent to be read by php. Some use url-encoding, others file_get_contents.
Anyway, it doesn't work for me. I'm sure there is ridiculously easy explanation for it but my code simply doesn't work (the request is sent, the backend answers but that message is more or less always the same: nothing seems to arrive there !
So in my controller I have :
var request_data = {
firstname: 'Quentin',
lastname: 'Hapsburg'
};
$http.post("lib/api/public/blog/post", JSON.stringify(request_data))
.success(function(data) {
console.log(data);
})
And in the php file:
$data = file_get_contents("php://input");
$data = json_decode($data, TRUE);
var_dump($data);
The result is NULL !
Any suggestions on where my error is ???
EDIT: This might have something to do with the rewriting rules but is not a duplicate since the same answer does not solve this question !
try using application/x-www-form-urlencoded
$http.post(urlBase, $httpParamSerializer(object), {
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
}).then(function(r) {
callback(r);
});
and then php will be able to access to your posted object using $_POST
Please use this js file. It will work
Index.html:
<html>
<head>
<script src="js/angular.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="mainCtrl">
sdadasdasd
</div>
<script src="app.js"></script>
</body>
</html>
app.js:
var app = angular.module("myApp", []);
app.controller("mainCtrl", function($scope,$http){
var request_data = {
firstname: 'Quentin',
lastname: 'Hapsburg'
};
$http.post("test.php", JSON.stringify(request_data)).success(function(data) {
console.log(data);
});
});