Unable to open sqlite DB file from js axios.get request - javascript

Unable to open sqlite DB file from js axios.get request:(console.log outputs exception message). The request may call my PHP controller to select data from DB and return it json-encoded.
An another side, PHP contoller makes it's job good: screenshot
In this way i trying send an axios request from Vue form: screenshot
or code:
Vue.createApp({
data: () => ({
processors:'',
memory:'',
drives:'',
motherboards:'',
cases:'',
}),
methods:{
fetchProcessors:function (){
axios.get('/src/controllers/getProcessors.php').then(
(response) => {
this.processors = response.data;
console.log(response);
});
}
},
created:function (){
console.log('vue is ok');
this.fetchProcessors();
}
}).mount(".js-form");
PHP controller code:
<?php
require_once __DIR__ . '/../../vendor/autoload.php';
use Doctrine\DBAL;
$connectionParams = [
'url' => 'sqlite3:///db/calc_db.sqlite3'
];
try {
$conn = DBAL\DriverManager::getConnection($connectionParams);
$data = $conn->fetchAllAssociative('SELECT name, cost FROM processors');
echo json_encode($data, JSON_THROW_ON_ERROR);
} catch (Exception $e) {
echo $e->getMessage();
}
I've tryed to:
give chmod 777 to whole project
make request with phpstorm tools (returns same exception message)
send const json from controller - it wotks good, proofs that js request and php controller working together normaly, trouble is in connection to DB file (i think so)
use sqlite driver instead of sqlite3
full stack trace

The problem was in 'path' param: i've launched my script from project root (working directory), so relative path to my DB builds correctly.
On web-server WD was a path, that i gave in request (controllers dir), so relative path to my DB builds incorrectly.
I've replaced path param like this and everything is OK:
$connectionParams = [
'path' => dirname(__DIR__, 2) . '/db/calc_db.sqlite3',
'driver' => 'pdo_sqlite'
];

Related

Laravel sanctum works in localhost, but returns 401 unauthenticated in live server [duplicate]

This question already has answers here:
Laravel sanctum unauthenticated
(13 answers)
Closed 3 days ago.
This is my 3rd post in a row on this issue, unfortunately I am not getting proper answer. I am developing an authentication system using laravel-sanctum in a laravel-vuejs app. The laravel-sanctum works fine (return user info from "/api/user" api) in the localhost. But when I am deploying in a live server, it returns 401 (unauthenicated) error.
my .env
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:WvNeYkRnJbXNcttmiAKe1blplUslHWIsRQpvnPt0mxA=
APP_DEBUG=true
APP_URL=https://subdomain.domain.com/
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
SESSION_DRIVER=cookie
SESSION_LIFETIME=120
SESSION_DOMAIN=subdomain.domain.com
SESSION_SECURE_COOKIE=false
SANCTUM_STATIC_DOMAIN=subdomain.domain.com
My sanctum.php
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 'subdomain.domain.com')),
'guard' => ['api'],
cors.php
'supports_credentials' => true,
auth.php
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'api' => [
'driver' => 'session',
'provider' => 'users',
],
],
From bootstrap.js
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] =
'XMLHttpRequest';
axios.defaults.withCredentials = true
Code from component (script)
mounted() {
axios.defaults.headers.common["Authorization"] = `Bearer ${this.token}`;
axios.get('/api/user').then(response => {
this.userInfo = response.data
})
}
I think you should define home url in the blade page you use vue app like this.
<script>
window.home = "<?php echo your-host-url ?>";
</script>
To make sure the API route is correct you add:
axios.get(window.home + '/api/user').then(response => {
this.userInfo = response.data
})
The solution is adding this to .htaccess of root folder (not only inside the public folder)
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

Laravel: API not found in production environment

I have created an API called "getservicedata" which returns data to be used in Vue.js component.The problem is I get a 404 status code on my production enviroment, which means the file cannot be found. Locally, this is not an issue, only on the production environment.
api.php file:
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Route::group(['middleware' => 'auth:sanctum'], function(){
// Create new API estimate
Route::apiResource('estimate', EstimateController::class);
// Get Service Data
Route::get('/services/getservicedata', [ServiceController::class, 'getServiceData']);
// Create new API Service
Route::apiResource('services', ServiceController::class);
});
ServiceController file:
public function getServiceData()
{
$services = Service::with('vendor')->get();
return $services;
}
Vue.js component:
methods: {
loadServices: function(){
axios.get('/api/services/getservicedata')
.then(response => {
this.services = response.data;
})
.catch(function(error){
console.log(error);
});
},
Please clear the route cache on the production. Still, you face the issue then check the route list of laravel with the below command and see route exists with which URL.
php artisan route:list
Thanks!

How to handle error from controller using PJAX in YII2?

I am using Yii2 Pjax widget which is unable to throw error from controller due to which I am unable to log error for users when there is any error coming from the controller.
PJAX code
<?php Pjax::begin([
'id' => 'createBucketPjax',
'timeout' => 4000,
'formSelector' => '#createBucketForm',
'enablePushState' => false,
'clientOptions' => [
'skipOuterContainers' => true,
'error' => new JsExpression("function(event) {
alert('Anything');
}"),
]
]); ?>
CONTROLLER code:
if(!$fieldModel->save()){
$transaction->rollBack();
//Here I want to send error
$error = $fieldModel->getErrorsString();
return [
'success' => false,'error' => $error
];
}else{
return $this->renderAjax('create', [
'model' => $model
]);
}
I have tried below clientOptions but not working
'error' => new JsExpression("function(event) {
alert('Please work');
}"),
Also used javascript but no help :-
$(document).on('pjax:error', function(event) {
console.log(event);
})
Is there any way from which I can send 404 from controller in yii2 ? That can actually resolve my problem
From the Yii2 Pjax docs.
In responding to the AJAX request, Pjax will send the updated body content (based on the AJAX request) to the client which will replace the old content with the new one. The browser's URL will then be updated using pushState. The whole process requires no reloading of the layout or resources (js, css)
You must deal with full form content and not with json.
So you code must look like following (always return the form html back):
if(!$model->save()){
$transaction->rollBack();
}
return $this->renderAjax('create', [
'model' => $model
]);

Meteor: Http Call return Undefined on response after an Http Response

I try to upload a file by encoding the content as base64 using a meteor app and a custom php script.
The php script is the following:
require_once '../vendor/autoload.php';
use WindowsAzure\Common\ServicesBuilder;
use MicrosoftAzure\Storage\Common\ServiceException;
use MicrosoftAzure\Storage\Blob\Models\ListBlobsOptions;
error_log("Method:".$_SERVER['REQUEST_METHOD'],0);
if($_SERVER['REQUEST_METHOD'] === 'OPTIONS'){
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization');
error_log("Options Called",0);
die();
} else {
error_log("Post Called",0);
function create_storage_connection()
{
return "DefaultEndpointsProtocol=https;AccountName=".getenv('AZURE_ACCOUNT').";AccountKey=".getenv('AZURE_KEY');
}
$connectionString=create_storage_connection();
$blobRestProxy= ServicesBuilder::getInstance()->createBlobService($connectionString);
$container_name=getenv('AZURE_CONTAINER');
$data=file_get_contents('php://input');
$data=json_decode($data,true);
try{
//Upload data
$file_data=base64_decode($data['data']);
$data['name']=uniqid().$data['name'];
$blobRestProxy->createBlockBlob($container_name,$data['name'],$file_data);
$blob = $blobRestProxy->getBlob($container_name, $data['name']);
//Download url info
$listBlobsOptions = new ListBlobsOptions();
$listBlobsOptions->setPrefix($data['name']);
$blob_list = $blobRestProxy->listBlobs($container_name, $listBlobsOptions);
$blobs = $blob_list->getBlobs();
$url=[];
foreach($blobs as $blob)
{
$urls[]=$blob->getUrl();
}
error_log("Urls:\n".implode(" , ",$urls),0);
header("Content-type: application/json");
$result=json_encode(['files'=>"sent",'url'=>$urls]);
error_log("Result: ".$result,0);
echo $result;
} catch(ServiceException $e) {
$code = $e->getCode();
$error_message = $e->getMessage();
header("Content-type: application/json");
echo json_encode(['code'=>$code,'message'=>$error_message]);
}
}
And on my meteor script I created a file named "imports/ui/File.jsx" having the following content:
import React, { Component } from 'react';
import {FileUpload} from '../api/FileUpload.js';
class File extends Component {
changeFile(e) {
e.preventDefault()
let files = document.getElementById('fileUpload');
var file = files.files[0];
var reader=new FileReader();
reader.onloadend = function() {
Meteor.call('fileStorage.uploadFile',reader.result,file.name,file.type)
}
reader.readAsDataURL(file);
}
render() {
return (
<form onSubmit={ this.changeFile.bind(this) }>
<label>
<input id="fileUpload" type="file" name="file" />
</label>
<button type="submit">UploadFile</button>
</form>
)
}
}
export default File;
And I also have a file named imports/api/FileUpload.js that handles the http call to the server:
import { Meteor } from 'meteor/meteor';
import { HTTP } from 'meteor/http'
export default Meteor.methods({
'fileStorage.uploadFile'(base64Data,name,mime) {
// this.unblock();
let http_obj={
'data':{
'data':base64Data,
'name':name,
'mime':mime
},
}
HTTP.call("POST","http://localhost/base64Upload/",http_obj,function(err,response){
console.log("Response:",response);
});
}
});
The problem is even though I get I successfull response from my server the:
console.log("Response:",response);
Does not print the returned json response from my server script to the console. Instead I get the following message (in my browser console):
Response: undefined
I cannot uinderstand why I get undefined on response even though the php script returns a response. Also if I console.log the err I get the following:
Error Error: network
Καταγραφή στοίβας:
httpcall_client.js/HTTP.call/xhr.onreadystatechange#http://localhost:3000/packages/http.js?hash=d7408e6ea3934d8d6dd9f1b49eab82ac9f6d8340:244:20
And I cannot figure out why does it happen.
Edit 1:
The meteor App does 2 Http calls 1 using OPTIONS method and one that uses POST
As requested when replaced the die() with:
var_dump($_SERVER['REQUEST_METHOD']); exit;
I get the response:
/home/pcmagas/Kwdikas/php/apps/base64Upload/src/public/index.php:14:string 'OPTIONS' (length=7)
Also on my network tab of the browser it says:
Please keep in mind that the meteor performs 2 http calls to the script one using http OPTIONS method and one that uses the http POST one. What I want to get is the one that uses the http POST one.
Edit 2:
I also tried to put a timeout of 2 seconds by changing the http_obj into:
let http_obj={
'data':{
'data':base64Data,
'name':name,
'mime':mime
},
'timeout':2000
}
But I get the following error:
Error Error: Can't set timers inside simulations
In the end I needed to make the method to run on server:
I did it by changing the imports/api/FileUpload.js into this: (I also removed unwanted code)
import { Meteor } from 'meteor/meteor';
import { HTTP } from 'meteor/http'
export const UploadedFile=null;
if(Meteor.isServer){
Meteor.methods({
'fileStorage.uploadFile'(base64Data,name,mime) {
// this.unblock();
let http_obj={
'data':{
'data':base64Data,
'name':name,
'mime':mime
},
// 'timeout':2000,
'headers':{
'Content-Type': 'application/json'
}
}
return HTTP.call("POST","http://localhost/base64Upload/",http_obj);
}
});
}
And putting this require into server/main.js resulting into this:
import { Meteor } from 'meteor/meteor';
import {FileUpload} from '../imports/api/FileUpload.js';
Meteor.startup(() => {
// code to run on server at startup
});
Also on imports/ui/File.jsx I call the method like that:
Meteor.call('fileStorage.uploadFile',reader.result,file.name,file.type,function(err,response){
console.log(response);
})
}

use mailgun api and send email with javascript?

I am trying to use mailgun.com for sending emails. But it happened that I need to send it with js (cause sometimes I built websites with rubyonrails, sometimes with python. And now I need to built a simple landing page with mail sending.
And hosting (which is free ad suits me only supports php which I don't know)
So I decided to use js and obfuscate this code and paste it somewhere in somelibrary.So no one will ever find my secret key)
Can someone help with translating some of this examples into js code?
This is python example:
def send_simple_message():
return requests.post(
"https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages",
auth=("api", "YOUR_API_KEY"),
data={"from": "Excited User <mailgun#YOUR_DOMAIN_NAME>",
"to": ["bar#example.com", "YOU#YOUR_DOMAIN_NAME"],
"subject": "Hello",
"text": "Testing some Mailgun awesomness!"})
This is c# example
public static IRestResponse SendSimpleMessage() {
RestClient client = new RestClient();
client.BaseUrl = new Uri("https://api.mailgun.net/v3");
client.Authenticator =
new HttpBasicAuthenticator("api",
"YOUR_API_KEY");
RestRequest request = new RestRequest();
request.AddParameter("domain",
"YOUR_DOMAIN_NAME", ParameterType.UrlSegment);
request.Resource = "{domain}/messages";
request.AddParameter("from", "Excited User <mailgun#YOUR_DOMAIN_NAME>");
request.AddParameter("to", "bar#example.com");
request.AddParameter("to", "YOU#YOUR_DOMAIN_NAME");
request.AddParameter("subject", "Hello");
request.AddParameter("text", "Testing some Mailgun awesomness!");
request.Method = Method.POST;
return client.Execute(request);
}
This is php example
# Include the Autoloader (see "Libraries" for install instructions)
require 'vendor/autoload.php';
use Mailgun\Mailgun;
# Instantiate the client.
$mgClient = new Mailgun('YOUR_API_KEY');
$domain = "YOUR_DOMAIN_NAME";
# Make the call to the client.
$result = $mgClient->sendMessage($domain, array(
'from' => 'Excited User <mailgun#YOUR_DOMAIN_NAME>',
'to' => 'Baz <YOU#YOUR_DOMAIN_NAME>',
'subject' => 'Hello',
'text' => 'Testing some Mailgun awesomness!'
));
This is rails example:
def send_simple_message
RestClient.post "https://api:YOUR_API_KEY"\
"#api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages",
:from => "Excited User <mailgun#YOUR_DOMAIN_NAME>",
:to => "bar#example.com, YOU#YOUR_DOMAIN_NAME",
:subject => "Hello",
:text => "Testing some Mailgun awesomness!"
end
Obfuscated code just slows down the naughty coder who is trying to mess up, its not a perfect layer of security. Since you say your host supports php use the php code. all you have to do is send a post request to the php script
example code considering you are sending using jQuery library for javascript
<?php
require 'vendor/autoload.php';
use Mailgun\Mailgun;
if(isset($_POST['variable1']) && isset($_POST['variable2']))
{
$msg = $_POST['variable1']." ".$_POST['variable1'];
$mgClient = new Mailgun('key');
$domain = "your domain";
$result = $mgClient->sendMessage($domain, array(
'from' => 'from adress',
'to' => 'to adress',
'subject' => 'some subject',
'html' => $msg
));
$result = objectToArray($result);
echo json_encode($result);
}
?>
jquery code to send post request
$("button").click(function(){
$.post("mailer.php",
{
variable1: "Donald Duck",
variable2: "Duckburg"
},
function(data, status){
console.log(data);
});
});
The above code sends a post request to your php file, where the php file validates if it contains the variables 1 and 2 and continues with the execution

Categories

Resources