dropzone not uploading, 400 bad request, token_not_provided - php

okay i've been trying this for like 2 hrs now and cant to make this work. dropzone cant upload any file. the server says "token not provided". im using laravel as backend and it uses jwt tokens for authentication and angular as front end. here's my dropzone config.
$scope.dropzoneConfig = {
options: { // passed into the Dropzone constructor
url: 'http://localhost:8000/api/attachments'
paramName: 'file'
},
eventHandlers: {
sending: function (file, xhr, formData) {
formData.append('token', TokenHandler.getToken());
console.log('sending');
},
success: function (file, response) {
console.log(response);
},
error: function(response) {
console.log(response);
}
}
};
and the route definition
Route::group(array('prefix' => 'api', 'middleware' => 'jwt.auth'), function() {
Route::resource('attachments', 'AttachmentController', ['only' => 'store']);
}));
and the controller method
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(Request $request)
{
$file = Input::file('file');
return 'okay'; // just until it works
}
the token is correct and is actually getting to the server (because i tried returning the token using Input::get('token') in another controller function and it works). can someone tell me what im doing wrong? im getting "400 Bad Request" with "token_not_provided" message...
thanks for any help. and i apologize for my bad english..

I'm not sure why appending the token to the form isn't working, but you could try sending it in the authorization header instead.
Replace
formData.append('token', TokenHandler.getToken());
With
xhr.setRequestHeader('Authorization', 'Bearer: ' + TokenHandler.getToken());

make sure you add the token to your call: Example you can add the toke as a parameter in your dropzone url parameter.
//If you are using satellizer you can you this
var token = $auth.getToken();// remember to inject $auth
$scope.dropzoneConfig = {
options: { // passed into the Dropzone constructor
url: 'http://localhost:8000/api/attachments?token=token'
paramName: 'file'
},
eventHandlers: {
sending: function (file, xhr, formData) {
formData.append('token', TokenHandler.getToken());
console.log('sending');
},
success: function (file, response) {
console.log(response);
},
error: function(response) {
console.log(response);
}
}
};

Related

Ajax GET request is empty despite correct query string parameter

Using a simple Ajax GET request to retrieve some data, it successfully checks if($request->ajax()) {} but then fails any validation because there is no data in the Request $request variable. This happens only on the production server, on localhost everything works fine.
The console shows the intended URL https://example.com/employeeInfo?id=1, then error 422 (Unprocessable Entity). Output from error: function(jqxhr, status, exception) { alert('Exception:', exception); } gives an empty alert message.
View
<script>
(function ($) {
$(document).ready(function() {
$(".team-pic").off("click").on("click", function() {
$id = $(this).data('id');
// Get data
$.ajax({
type: 'GET',
url: 'employeeInfo',
data: {'id':$id},
success: function(data){
var obj=$.parseJSON(data);
// Show output...
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
});
});
}(jQuery));
</script>
Route
Route::get('/employeeInfo', 'EmployeeController#get');
Controller
public function get(Request $request) {
if($request->ajax()) {
$this->validate($request, [
'id' => 'required|integer',
]);
// Id
$employee = Employee::find(request('id'));
// Create output
$data = ...
echo json_encode($data);
}
}
If I were you, I would use a RESTful API with route model binding, specifically the explicit binding.
RouteServiceProvider.php
public function boot()
{
parent::boot();
Route::model('employee', App\Employee::class);
}
Route
Route::get('api/employees/{employee}', 'EmployeeController#get');
Controller
public function get(Employee $employee)
{
// The id being valid is already done by forcing it to be an Employee
// It is also an ajax call because it is going to the api route
// This will json_encode the employee object.
return $employee;
}

Call to a member function getClientOriginalName() on null

I can upload my file using to amazon s3 bucket successfully using my api and i can get a response:
But when i integrate this api into my application it says Call to a member function getClientOriginalName() on null i dont know where i am doing wrong:
My Api method:
public function uploadToAws(Request $request) {
$file = $request->file('image');
$imageName = 'company_logo/' . $file->getClientOriginalName();
Storage::disk('s3')->put($imageName, file_get_contents($file));
Storage::disk('s3')->setVisibility($imageName, 'public');
$url = Storage::disk('s3')->url($imageName);
$resultArray = ['status' => 1, 'message' => 'File uploaded to s3 bucket!', 'dataArray' => $url];
return Response::json($resultArray, 200);
}
and my response of this api:
{
"status": 1,
"message": "File uploaded to s3 bucket!",
"dataArray": "https://spikessales.s3.amazonaws.com/company_logo/template3.jpg"
}
I can perfectly upload file to s3 bucket using this api:
But when i integrate to my application view it says Call to a member function getClientOriginalName() on null i dont where i am wrong:
This view code using ajax call:
///upload logo sec
$(document).on('click', '.browse', function () {
var file = $(this).parent().parent().parent().find('.changefle');
file.trigger('click');
});
$(document).on('change', '.changefle', function () {
var imagename = "";
$.each($(".changefle")[0].files, function (i, file) {
imagename = file.name;
});
$.ajax({//Process the form using $.ajax()
type: 'post', //Method type
url: 'http://127.0.0.1:8000/api/upload_aws', //Your form processing file
URL
data: {
image: imagename
}, //Forms name
dataType: 'json',
success: function (data) {
console.log(data);
// localStorage.setItem("set-compylogo", companylogo);
},
error: function (data) {
console.log("error");
}
Your help will be highly appreciated!
It might be your ajax need more headers to upload file. or may be it need this:
$.ajax({
headers: {
'X-CSRF-TOKEN': your_crsf_token,
'Content-type: text/html;charset=ISO-8859-1'
},
...
});
For further information, you might want to check this out: AJAX File Upload with XMLHttpRequest
You are sending a string (image name) instead of a FILE object. To use those methods laravel needs a file object. So imagename = file; instead of imagename = file.name

Cakephp 3.4 AJAX request throws 403 forbidden error

I have been trying to send some data to a controller via AJAX but for the life of me I can`t seem to make it work; everytime I make the request, a 403 forbidden error is thrown.
this is the ajax request:
$.ajax({
type: 'post',
url:"<?php echo Router::url(array('controller'=>'Atls','action'=>'saveTime', '_ext' => 'json'));?>",
dataType: 'json',
data: {atl_id: idTimerPaused, time: actual_time},
beforeSend: function(xhr){
},
success: function (response) {
console.log('Nailed It');
},
error: function(jqXHR, exception){
console.log(jqXHR);
}
});
return false;
the controller action:
public function saveTime()
{
if ($this->request->is('post') && $this->request->is('ajax')) {
$content = $this->request->getData();
$query = $this->Atls->query();
$result = $query
->update()
->set(
$query->newExpr('actual_time = '. $content['time'])
)
->where([
'id' => $content['atl_id']
])
->execute();
$this->set(compact('content'));
$this->set('_serialize', ['content']);
$this->render('ajax_response', 'ajax');
}
}
I have loaded the extensions on the routes.php file (Router::extensions('json', 'xml');)
The request handler is also loaded and the function is allowed:
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
}
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Auth->allow('saveTime');
//Change layout for Ajax requests
$this->viewBuilder()->layout('appTemplate');
if ($this->request->is('ajax')) {
$this->viewBuilder()->layout('ajax');
}
}
that "ajax_response" view has also been added.
I can't see where the problem could be. So any help I can get to work this out would be much appreciated.
Did you use the 'Csrf'-Component? In my case this was the problem.
https://book.cakephp.org/3.0/en/controllers/components/csrf.html#csrf-protection-and-ajax-requests
When you got an 403 forbidden error in most cases the session is expired and the user has to login again.

ajax request in laravel 5

im not sure how to do this in laravel. Im trying to do a simple ajax request to my controller. Then in my controller return the values that i sent through so i can console.log the data.
However im having a problem doing so.
Ajax Request:
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
jQuery.ajax({
url:'/group/create',
type: 'GET',
data: {
name: groupName,
colour: "red"
},
success: function( data ){
console.log(data);
},
error: function (xhr, b, c) {
console.log("xhr=" + xhr + " b=" + b + " c=" + c);
}
});
Route:
Route::get('/group/create', ['middleware' => 'auth', 'uses' => 'GroupController#create']);
Controller:
public function create()
{
$data = Request::all();
return json_encode($data);
}
Now when i console.log the returned data it shows at the exact html for the page im on. Any ideas?
Check on the browser console-network-lastprocess- preview, it could show you the error.
Also you can "console log" from the controller using Log::info('useful information') and it will show it to you at storage/logs/laravel.log
You should use Laravel's JSON return: return response()->json(['name' => 'Abigail', 'state' => 'CA']);
But also what you're doing is actually calling a GET with data however it should be a POST in this case. If you have to provide data to a controller, it's a POST and you can just return the data that way.
So change your AJAX to be POST and then you can use the Request::all() to get all data, and return it via JSON.

Defined route throwing controller method not found laravel 4

I have a route defined in routes.php file but when i make an ajax request from my angular app, i get this error
{"error":{"type":"Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException","message":"Controller method not found.","file":"C:\\xampp\\htdocs\\tedxph\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Controllers\\Controller.php","line":290}}
this is my routes file
/*
|--------------------------------------------------------------------------
| Api Routes
|--------------------------------------------------------------------------
*/
Route::group(array('prefix' => 'api'), function() {
//Auth Routes
Route::post('auth/login', 'ApiUserController#authUser');
Route::post('auth/signup', 'ApiUserController#registerUser');
/* Persons */
Route::group(array('prefix' => 'people'), function() {
Route::get('{id}', 'ApiPeopleController#read');
Route::get('/', 'ApiPeopleController#read');
});
/* Events */
Route::group(array('prefix' => 'events'), function() {
Route::get('{id}', 'ApiEventsController#read');
Route::get('/','ApiEventsController#read');
});
});
Accessing the same url (http://localhost/site/public/api/auth/signup) from a rest client app on chrome does not give any errors, what could be wrong?
this is the angular code from my controller
$rootScope.show('Please wait..registering');
API.register({email: email, password: password})
.success(function (data) {
if(data.status == "success") {
console.log(data);
$rootScope.hide();
}
})
.error(function (error) {
console.log(error)
$rootScope.hide();
})
more angular code
angular.module('tedxph.API', [])
.factory('API', function ($rootScope, $http, $ionicLoading, $window) {
//base url
var base = "http://localhost/tedxph/public/api";
return {
auth: function (form) {
return $http.post(base+"/auth/login", form);
},
register: function (form) {
return $http.post(base+"/auth/signup", form);
},
fetchPeople: function () {
return $http.get(base+"/people");
},
fetchEvents: function() {
return $http.get(base+"/events");
},
}
});
It'd help to see the code you're using to make the angular request, as well as the header information from Chrome's Network -> XHR logger, but my first guess would be Angular is sending the AJAX request with the GET method instead of the POST method. Try changing Angular to send an explicit POST or change routes.php so auth/signup responds to both GET and POST requests.
Update looking at your screen shots, the AJAX request is returning an error 500. There should be information logged to either your laravel.log file or your PHP/webserver error log as to why the error is happening. My guess if your Angular request sends different information that your Chrome/REST-app does, and that triggers a code path where there's an error.
Fixed the problem, turns my controller was calling an undefined method in the controller class.
Renamed the method correctly and the request now works, thanks guys for the input.

Categories