I have a simple Vue app in which I am sending POST request with options (table filtering variables) to the back-end. I want to be able to destructure the object and debug it in my TestController in Laravel 8, so I want to send the options to web.php via URL, not to api.php. Since options is an object, I cannot just drop it in the URL.
Ultimately I want to be able to preview my Laravel respond in browser, so I know it returns correct data from server.
So how can I achieve this?
in Vue FormComponent <form #submit="formSubmit"> and script
function formSubmit(e) {
e.preventDefault();
let currentObj = this;
axios.post('/formSubmit', {
name: this.name,
description: this.description
}).then(function(response) {
currentObj.output = response.data;
console.log(currentObj);
}).catch(function(error) {
currentObj.output = error;
});
}
Firstable, create POST route for your request. Then just make POST request to this route url and put your POST params (your object) to request body. You can use Axios as example
let filterOptions = {...};
axios.post(url, filterOptions).then().catch();
UPD And response for your request you can see in browser developer console on network tab
Related
I know we have the stateless() and and getTargetUrl() methods, than i am trying this at my controller:
public function socialRedirect($provider){
return Socialite::with($provider)->stateless()->redirect()->getTargetUrl();
}
The problem is that in my SPA front end, i can't make a sucessfull request to the provided url as like in the code below:
async facebookLogin() {
try {
const url = await this.$axios.$get('/auth/social/facebook')
this.$axios.$get(url)
} catch (error){
console.log(error)
}
},
I get CORS related stuff errors:
OPTIONShttps://www.facebook.com/v3.3/dialog/oauth?client_id=240805606930310&redirect_uri=http://localhost:8000/api/auth/social/facebook/callback&scope=email&response_type=code
CORS Missing Allow Origin
What am i doing wrong? I am specially confused since i can access the URL by copying it and pasting in another browser tab, but i can't sucessfully make the AJAX request to it.
If I do this in my Vue.js script component
getResumeAPIData(id){
// declare a response interceptor
axios.interceptors.response.use((response) => {
// do something with the response data
console.log('Response was received');
return response;
}, error => {
// handle the response error
return Promise.reject(error);
});
// sent a GET request
axios.get(`api/resume-data-returns/${id}`)
.then((response)=>{
this.RelationTable = response.data
console.log(this.RelationTable);
})
},
I get a response like this
{"id":1,"name":"userlocalvm","email":"userlocalvm#v","email_verified_at":null,"type":"user","bio":"Why","photo":"1606931001.jpeg","created_at":"2020-12-02T16:01:00.000000Z","updated_at":"2020-12-02T17:43:21.000000Z"}
Because of my Laravel api.php->Controller Backend code
$findOrFailId = Resumes::findOrFail($forEachId);
$foreignKeyOfResTable = $findOrFailId->user_id;
return User::findOrFail($foreignKeyOfResTable);
But if I do it like this as
// sent a GET request
axios.get(`api/resume-data-returns/${id}`)
.then((response)=>{
this.RelationTable = response.data.created_at
console.log(this.RelationTable);
})
The added dot then the property name of the column
response.data.created_at
I get a response
undefined
Sorry if this is a silly question as I am still quite a rookie in programming in general and the jargons that comes with it and I want learn and master javascript and php so bad!
It might be that the response is inside another data object. You might have to do something like this:
response.data.data.created_at
I am working on a project for my self learning that has laravel in the backend and running react native in the front end. I have implemented the login and register screen for my apps. Now I am trying to connect it to my laravel server through its api routes. I was first having CORS issue so I solved it by making a new middleware and editing the kernel.php file as stated in this thread.
CORS Issue with React app and Laravel API
Now I tried to run some tests first with get request my submit function in react is
handleSubmit = async() => {
const email = this.state.email
const pass = this.state.password
const proxyurl = "https://cors-anywhere.herokuapp.com/";
/*TEST FOR GET REQUEST */
let response = await fetch(`http://mobileprediction/api/user?email=${email}&pass=${pass}`, {
headers: {
"Content-Type" : "application/json",
"Accept" : "application/json"
},
})
let result = await response.json()
console.log(result)
}
and my api.php file in the routes of laravel was
Route::get("/user", function (Request $request) {
return $request;
});
and it gave the desired output, but then when I tested the same way with a post request I am getting an empty array no matter what and I am unable to figure out what the problem is
the handlesubmit function in my react native app is
handleSubmit = async() => {
const email = this.state.email
const pass = this.state.password
/*TEST FOR POST REQUEST */
let response = await fetch(`http://mobileprediction/api/user`, {
method: "POST",
header : {
"Content-Type" : "application/json",
"Accept" : "application/json"
},
body : JSON.stringify({
emailid : email,
password : pass
}),
})
let result = await response.json()
console.log(result)
}
and api.php file in laravel is
Route::get("/user", function (Request $request) {
return $request;
});
Route::post("/user", function(Request $request) {
return $request;
});
I think you write your routes in web.php, for your API could write the endpoints in api.php.
Try to comment VerifyCsrfToken middleware in app/Http/Kenrel.php.
it has security issue, but you can do it in your learning steps.
[ https://laravel.com/docs/6.x/routing ] [search CSRF in this link]
Any routes pointing to POST, PUT, or DELETE routes that are defined in the web routes file should include a CSRF token field.
So what I understood is that from the fetch request in react native its not sending just the inputs but rather a page with a body that has json formatted key values. So I cant access data in my server as
$request->param
or with
request("param")
you could get the json formatted string with
$request->json()->all()
but still I couldnt get to the individual values
for me what was working is to get all the contents and then access the values with
$postInput = file_get_contents('php://input');
$data = json_decode($postInput, true);
return ["email" => $data["emailid"] ];
need some help. I'm trying to fetch data from my db using axios. My backend is Laravel. I have a 200 status http request but it returns the whole html not the data I'm expecting.
Here is my code for route
Route::get('/home', 'PostController#ajaxCall');
Route::post('/home', 'PostController#store');
Route::get('/{any?}', function () {
return view('welcome');
});
Here is my code for Home.vue for Axios request
export default {
components: {addForm},
data () {
return{
posts:[]
}
},
created() {
axios.get('/home').then(response => this.posts = response.data);
}
}
For my controller
public function ajaxCall(){
return response(Post::all());
}
It looks like you get to the ajaxCall() method by using the route '/home', but with axios, you are hitting "/" which returns a view called Welcome. Maybe you need to change the path you use in axios to '/home'?
It might be late but maybe someone else is looking for the solution
I was also facing this in SPA using laravel and VUE.
Route::get('/{any}', 'SinglePageController#index')->where('any', '.*');
SPA has this route, so whenever you write any other get route your app will redirect you to the home page, to avoid this either move this route at the end of your web.php
or write your other routes in api.php file.
In my case i solved it by changing the GET method to POST method.
Try that. It might help
I have developed a template (feedheader.hbs) which I am rendering in my feed template like {{ render 'feedheader' feedheader}}.This feedheader contains the username and profile pic of user.I need to send the the requests to http://example.com/api/users/profile/?targetuser=-1 along with my auth header to get the user details.So I made a controller for feedheader and made the ajax requests.I am using ember-simple-auth (fb login ) for authorization.
controller.js
import Ember from 'ember';
import OAuth2Bearer from 'ember-simple-auth/authorizers/oauth2-bearer';
const { service } = Ember.inject;
export default Ember.Controller.extend(OAuth2Bearer,{
session:service('session'),
init:function(){
this.get('session').authorize('authorizer:application', (headerName, headerValue) => {
const headers = {};
headers[headerName] = headerValue;
Ember.$.ajax('http://example.com/api/users/profile/?targetuser=-1', { headers });
});
}
});
But it throws an error in console
"Uncaught Error: Assertion Failed: Expected hash or Mixin instance, got [object Function]"
authorizers(application.js)
import OAuth2Bearer from 'ember-simple-auth/authorizers/oauth2-bearer';
export default OAuth2Bearer.extend();
The authorizers is working fine in my adapter.There is some simple thing I am missing and not able to fix this.Please tell how to send the ajax request with my authorizers header.
The way you're sending the headers doesn't look right to me. Instead of
Ember.$.ajax('http://example.com/api/users/profile/?targetuser=-1', { headers });
it should be
Ember.$.ajax('http://example.com/api/users/profile/?targetuser=-1', { headers: headers });