I am trying to get the id of a click event in axios vue.js in laravel, but I am getting the url wrong in console.
http://{mylink}/messages/getMessages1
instead of
http://{mylink}/messages/getMessages/1
I want the output as the second url.
My method in file.js looks like this:
methods:{
messages:function(id){
let vm = this;
this.$http
.get('messages/getMessages' + id)
.then(response => {
console.log(response.data);
vm.privateMsgs = response.data;
})
.catch(function (error) {
console.log(error.response);
});
}
the route looks like this:
Route::get('/messages/getMessages/{id}','Messages#getuser');
and the controller looks like this:
public function getuser($id){
echo $id;
}
please guide me to make this correct.
You are missing the slash in your axios request. It should be:
.get('/messages/getMessages/' + id)
I checked and the code is working properly.
messages:function(id){
var self = this;
this.$http.get('/messages/getMessages/' + id)
.then(response => {
console.log(response.data);
this.privateMsgs = response.data;
})
.catch(function (error) {
console.log(error.response);
});
}
Related
In controller laravel: I use box/spout , I save the excel file in a separate folder, and i create a variable that points to the folder where the file is saved, and i return the vuejs view to download that file
$path = '/files/'.$name;
$urlFile = url('/files/'.$name);
var_dump($urlFile);
// Result:
http://localhost.loca/file/data.xlsx
I return view vuejs:
return response()->json($urlFile);
View vuejs :
methods: {
// event button click
clickButton() {
axios
.get("/api/export")
.then((res) => {
console.log(res.data) // http://localhost.loca/file/data.xlsx
// I want to download this link !
})
.catch((error) => {
console.log(error);
});
}
}
Please give me idea download link ? Thanks
Update: I use window.open(res.data) but it doesn't work
Try to create an anchor and click on it programmatically to download the file :
.then((res) => {
console.log(res.data) // http://localhost.loca/file/data.xlsx
//create and append anchor download to body
const downloadAnchor = document.createElement("a");
downloadAnchor.setAttribute("href", "http://localhost.loca/file/data.xlsx");
downloadAnchor.setAttribute("download", "data.xlsx");
document.body.appendChild(downloadAnchor);
downloadAnchor.click();
//remove anchor download
document.body.removeChild(downloadAnchor);
})
If window.open doesn't work you can try this:
function download(url) {
const a = document.createElement('a')
a.href = url
a.download = url.split('/').pop()
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
And then call the download function in your method:
methods: {
// event button click
clickButton() {
axios
.get("/api/export")
.then((res) => {
console.log(res.data) // http://localhost.loca/file/data.xlsx
download(res.data)
})
.catch((error) => {
console.log(error);
});
}
}
Hi developers I have currently problem this project is an old project where the developer created. right now, we need to adjust some of there functionality. Right now I already extract the files to my localhost folder and now work without error on run watch and artisan serve. So the problem here is on login on the console it shows that http://localhost:8000/project/oauth/token 405 (Method Not Allowed), I really don't understand why this shows on the localhost however on the live server it works.
This project created using Vue Js and Laravel for the backend.
I will show you guys the authentication function.
Login Function:
authenticate(){
this.login_alert = false
this.$validator.validateAll().then((result)=>{
if(result){
const self = this;
const authUser = {}
try{
const data = {
username: this.email,
password: this.password,
remember: this.remember_me,
client_id: '2',
client_secret: 'secret',
grant_type : 'password',
scope : ''
}
this.$store.dispatch('AUTH_REQUEST',data)
.then(response=>{
console.log(data);
authUser.access_token = response.access_token
authUser.refresh_token = response.refresh_token
authUser.expires_in = response.expires_in
window.localStorage.setItem('project_token',JSON.stringify(authUser))
/*LOGIN*/
this.login_alert = false
this.loading = false
window.location.reload()
})
.catch(error=>{
this.login_alert = true
window.localStorage.removeItem('project_token')
this.loading = false
})
}catch(err){
console.log(err);
}
}
})
}
For the AUTH REQUEST:
AUTH_REQUEST:({commit,dispatch},obj)=>{
return new Promise((resolve,reject) => {
axios({
url: '/project/oauth/token',
data: obj,
method:'post',
config:'JSON'
})
.then(response=>{
if(response.status == 200){
resolve(response.data);
}
})
.catch(error=>{
reject(error);
localStorage.removeItem('project_token');
commit('AUTH_ERROR',error);
})
})
},
Hope some one experience this. thanks.
In my case, the compilation of the route should be specified properly, for example
async purchaseDelete(purchase) {
Csrf.getCookie();
return Api.delete('/api/purchase_settings/${purchase.id}');
},
the single tick on the axios delete method didnt represent correctly
async purchaseDelete(purchase) {
Csrf.getCookie();
return Api.delete(`/api/purchase_settings/${purchase.id}`);
}
When changed to back ticks, it responded with the correct result
In defaut registration API, I need to uplaod the image of user in registration API. So how could I manage it ? I'm sending in a formData and it works fine. I can see (binary) in network.
I tried to add image field and it works in admin panel but from API side I tried to send the file in key names like files, profileImage.
I didn't get the error in res. I got success in res.
Issue: When I reload the admin panel, I didn't get user's profile image.
Try this way. I used in react and it works fine for me.
signUpHandler = () => {
console.log("SignUp data ::: ", this.state);
let data = {
username: this.state.signUpForm.username.value,
phone: this.state.signUpForm.phone.value,
email: this.state.signUpForm.email.value,
password: this.state.signUpForm.password.value
}
axios.post('http://0.0.0.0:1337/auth/local/register', data)
.then(res => {
console.log(res);
return res.data.user.id;
})
.then(refId =>{
const data = new FormData();
data.append('files', this.state.selectedFile);
data.append('refId', refId);
data.append('ref', 'user');
data.append('source', 'users-permissions');
data.append('field', 'profileImage');
return axios.post('http://0.0.0.0:1337/upload', data)
})
.then(res =>{
console.log(res);
alert("You registered successfully...");
this.props.history.push('/login');
})
.catch(error =>{
console.log(error);
})
}
First, you will have to customize your user-permission
To do so, you will have to understand this concept: https://strapi.io/documentation/3.0.0-beta.x/concepts/customization.html
Then you will have to find the function you want to update - in your case, the register function.
And tada here it is https://github.com/strapi/strapi/blob/master/packages/strapi-plugin-users-permissions/controllers/Auth.js#L383.
So you will have to create ./extensions/users-permissions/controllers/Auth.js with the same content as the original file.
Then you will have to add
const { parseMultipartData, sanitizeEntity } = require('strapi-utils');
const uploadFiles = require('strapi/lib/core-api/utils/upload-files');
on the top of your file.
And in your function use this
const { data, files } = parseMultipartData(ctx); to parse data and files.
Then you will have to replace ctx.request.body by data to make sure to use the correct data.
After that you will have to add this after the user creation line
https://github.com/strapi/strapi/blob/master/packages/strapi-plugin-users-permissions/controllers/Auth.js#L510
if (files) {
// automatically uploads the files based on the entry and the model
await uploadFiles(user, files, { model: strapi.plugins['users-permissions'].models.user })
}
Solution for Strapi v4:
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer XXXX");
var formdata = new FormData();
formdata.append("files", fileInput.files[0], "XXX.png");
formdata.append("refId", "46");
formdata.append("field", "image");
formdata.append("ref", "plugin::users-permissions.user");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: formdata,
redirect: 'follow'
};
fetch("http://localhost:1337/api/upload", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
I am trying to show client information details in the modal. After clicking #click="showDetails(props.row.id)".
I am using axios.get in method and returning the data. Now, It's returning the data as PromiseValue object. How to access PromiseValue to show the value in HTML. Would someone help me please to solve the problem! I am trying like below -
<button #click="showDetails(props.row.id)"><i class="fas fa-eye"></i></button>
And in script-
<script type="text/javascript">
import axios from 'axios';
export default {
data(){
return{
leftPanelVisiblity: false,
singleData: '', }
},
methods:{
showDetails(id){
let b = axios.get('/api/clients/'+id)
.then(function (response) {
return response.data;
}).catch(error => {
alert(error);
});
//console.log(b);
this.singleData = b;
this.leftPanelVisiblity = true
},
}
}
</script>
And finally, I want to access or show the data in the leftPanelVisiblity modal like -
<p>Name: {{ this.singleData.name }}</p>
Or
<p>Name: {{ this.singleData.email }}</p>.
You cannot assign the Axios call to a variable while using Promises (unless you are using await/async).
Instead you should be running the logic within the then callback. Otherwise to the synchronous nature of JavaScript it will run before the request has completed. Your code should look something like this:
methods:{
showDetails(id){
axios.get('/api/clients/'+row.id).then(response => {
//Logic goes here
this.singleData = response.data
this.leftPanelVisibility = true
}).catch(error => {
alert(error);
});
}
}
You need to assign a variable the response of your axios:
showDetails(id){
axios.get('/api/clients/'+id)
.then(function (response) {
this.singleData = response.data;
}).catch(error => {
alert(error);
});
console.log(this.sigleData);
this.leftPanelVisiblity = true
},
im having this issue where i send a request to the API to retrieve all users, the login function is called(index.vue) when called it tries to go to api/users/all which in this case should return all the users in that collection.
using Postman the API returns the correct results and if i console.log the output in the routeUsers before i send the response back, it outputs all the correct data to the console
when it returns to index.vue, the response status code is 0.
ive had a look online and some things are mentioning about CORS Headers but i dont think thats applicable to me and other things about the response has been cancelled,
can anyone shed some light on this for me and help me try to fix it?!
API main.js
var app = express();
var users = require('./routes/routeUsers');
app.use('/users', users);
module.exports = app;
api/models/users.js
var db = require('../Utilities/db')
module.exports.all = function(cb) {
var collection = db.get().collection('users')
collection.find().toArray(function(err, docs) {
cb(err, docs)
})
}
api/routes/routeUsers.js
var express = require('express')
, router = express.Router()
var user = require('../models/users');
router.get('/all', function(req, res) {
user.all(function(err, users) {
res.send(users);
})
})
Index.vue
export default {
data: function () {
return {
username: '',
password: '',
users: []
}
},
methods: {
login: function() {
Vue.http.get('/api/users/all').then((response) => {
console.log("SUCCESS",response);
this.users = response.body;
console.log(users);
}, function (error) {
console.log("Error", error.status); // handle error
});
}
}
};
The issue was that the inputs were in a form tag. removed Form tag and worked fine.