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!
Related
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'
];
I'm learning Laravel with React.js but I can't figure out why my simple get request won't work. I get a 404 error. I've seen a similar question asked on SO and I've tried running composer require barryvdh/laravel-cors on the command line but it still doesn't work.
How can I rectify this?
Here's react code:
constructor(props) {
super(props);
this.axiosGet = this.axiosGet.bind(this);
}
axiosGet(e) {
e.preventDefault();
axios.get('/thank-you')
.then(response => {
console.log(response);
});
}
render() {
<Form onSubmit={this.axiosGet}>
...
</Form>
}
Here's api.php
use App\Http\Controllers\MailController;
Route::get('/thank-you', [MailController::class,'index']);
Here's MailController.php
public function index() {
return "Testing";
}
your route is /api/thank-you. When you are using API routes. API comes in front of your routes.
Change your axios.get('/thank-you') as axios.get('/api/thank-you')
I am using strapi to create APIs.
I want to implement my own Registration API and Login API.
I checked the documentation of strapi but i am not finding any custom API for this.
can any one help me on this?
Same answer, but in more detail:
Strapi creates an Auth controller automatically for you and you can overwrite its behavior.
Copy the function(s) you need (e.g. register) from this file:
node_modules/strapi-plugin-users-permissions/controllers/Auth.js
to:
your_project_root/extensions/users-permissions/controllers/Auth.js
Now you can overwrite the behavior, e.g. pass a custom field inside the registration process {"myCustomField": "hello world"} and log it to the console:
async register(ctx) {
...
...
// log the custom field
console.log(params.myCustomField)
// do something with it, e.g. check whether the value already exists
// in another content type
const itExists = await strapi.query('some-content-type').findOne({
fieldName: params.myCustomField
});
if (!itExists) {
return ctx.badRequest(...)
} else {
console.log('check success')
}
}
Actually, strapi creates an Auth controller to handle these requests. You can just change them to fit in your need.
The path to the controller is:
plugins/users-permissions/controllers/Auth.js
in order to create custom users-permissons apis on server side you have to create
src/extensions/users-permissions/strapi-server.js
and in that file can write or override existing user-permissions plugin apis
here is the example for users/me
const _ = require('lodash');
module.exports = (plugin) => {
const getController = name => {
return strapi.plugins['users-permissions'].controller(name);
};
// Create the new controller
plugin.controllers.user.me = async (ctx) => {
const user = ctx.state.user;
// User has to be logged in to update themselves
if (!user) {
return ctx.unauthorized();
}
console.log('calling about meeeeeeeeeee------')
return;
};
// Add the custom route
plugin.routes['content-api'].routes.unshift({
method: 'GET',
path: '/users/me',
handler: 'user.me',
config: {
prefix: '',
}
});
return plugin;
};
I didn't find a solution for this problem. I'm currently working with the CRUD Master-Detail Application WebIDE template and added some custom functions with OData calls. When running the app with mock server it loads the mock data. So far so good. But if I send a read request to the mock server it throws a 404 not found error.
Request URL
https://webidetesting[...].dispatcher.hana.ondemand.com/here/goes/your/serviceurl/MyEntity(12345)
Here's the mock server part in my index file flpSandboxMockServer.html:
<script>
sap.ui.getCore().attachInit(function() {
sap.ui.require([
"my/project/localService/mockserver"
], function (mockserver) {
// set up test service for local testing
mockserver.init();
// initialize the ushell sandbox component
sap.ushell.Container.createRenderer().placeAt("content");
});
});
</script>
The OData read call looks like:
onRemoveMyEntityBtnPress: function () {
let oEntityTable = this.byId("lineItemsList");
let aSelectedItems = oEntityTable.getSelectedItems();
let oModel = this.getModel();
for (let oSelectedItem of aSelectedItems) {
let sBindingPath = oSelectedItem.getBindingContext().getPath();
let sGuid = this._selectGuidFromPath(sBindingPath);
this._loadEntityFromService(sGuid, oModel).then((oData) => {
// Next step: change a property value
}).catch((oError) => {
jQuery.sap.log.error(oError);
});
}
if (oModel.hasPendingChanges()) {
oModel.submitChanges();
}
},
_loadEntityFromService: function (sGuid, oModel) {
return new Promise((resolve, reject) => {
oModel.read(`/MyEntity(${sGuid})`, {
success: (oData) => {
resolve(oData);
},
error: (oError) => { // call always ends up here with 404 error
reject(oError);
}
});
});
},
Does someone have an idea what I else have to do to send my read request to the mock service?
Finally found the solution!
I used the OData entity type to read my entity. I changed the destination to my entity set and now it doesn't throw a 404 error.
First, I try to make a custom visualization in Kibana with learning here.
Then, I want my custom visualization to display like the clock how many hits my elasticsearch index has dynamically .
So, I changed some codes in above tutorial but they don't work.
Chrome Devtools tells says Error: The elasticsearch npm module is not designed for use in the browser. Please use elasticsearch-browser
I know I had better use elasticsearch-browser perhaps.
However, I want to understand what is wrong or why.
public/myclock.js
define(function(require) {
require('plugins/<my-plugin>/mycss.css');
var module = require('ui/modules').get('<my-plugin>');
module.controller('MyController', function($scope, $timeout) {
var setTime = function() {
$scope.time = Date.now();
$timeout(setTime, 1000);
};
setTime();
var es = function(){
var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
host: 'localhost:9200',
log: 'trace'
});
client.search({
index: 'myindex',
}).then(function (resp) {
$scope.tot = resp.hits.total;
}, function (err) {
console.trace(err.message);
});
};
es();
});
function MyProvider(Private) {
...
}
require('ui/registry/vis_types').register(MyProvider);
return MyProvider;
});
public/clock.html
<div class="clockVis" ng-controller="MyController">
{{ time | date:vis.params.format }}
{{tot}}
</div>
Thank you for reading.
Looks like the controller in angularjs treats the elasticsearch javascript client as if it was accessing from the browser.
To elude this, one choice will be by building Server API in index.js and then make kibana access to elasticsearch by executing http request.
Example
index.js
// Server API (init func) will call search api of javascript
export default function (kibana) {
return new kibana.Plugin({
require: ['elasticsearch'],
uiExports: {
visTypes: ['plugins/sample/plugin']
},
init( server, options ) {
// API for executing search query to elasticsearch
server.route({
path: '/api/es/search/{index}/{body}',
method: 'GET',
handler(req, reply) {
// Below is the handler which talks to elasticsearch
server.plugins.elasticsearch.callWithRequest(req, 'search', {
index: req.params.index,
body: req.params.body
}).then(function (error, response) {
reply(response);
});
}
});
}
});
}
controller.js
In the controller, you will need to call GET request for above example.
$http.get( url ).then(function(response) {
$scope.data = response.data;
}, function (response){
$scope.err = "request failed";
});
In my case, I used url instead of absolute or relative path since path of dashboard app was deep.
http://[serverip]:5601/iza/app/kibana#/dashboard/[Dashboard Name]
*
Your here
http://[serverip]:5601/iza/[api path]
*
api path will start here
I used this reference as an example.