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.
Related
I set a cookie and I usually access it like this when I need to test a "protected" request.
beforeAll(async () => {
await db.connect();
//sign my user and get the token
const response = await request(app).post("/gettoken").send(credentials);
TOKEN = response.headers["set-cookie"].pop().split(";")[0];
})
//test exemple
it("exemple", async () => {
const result = await request(app).post("/path").set(`Cookie`, TOKEN).send(data);
});
So far I had no problem with it but in one of my function that I want to test I have this line:
user = await getUser(req.cookies.token);
the function getUser is pretty simple:
const userToken = jwt.verify(token, process.env.JWTPRIVATEKEY);
user = await User.findOne({ _id: userToken.payload._id });
return user;
Seems like supertest does not work with req.cookies. Is there any way to set "req.cookies.token" during my test ?
I'm going to answer my own question but please, be aware that I have no idea why it works. Actually I was a bit desperate to not find any solution so I did try something without any hope but, surprisely, it worked.
so basically after restarting docker my console.log were all similars (npm run test vs test with postman)
module.exports.getUser = async (token) => {
console.log(token);
console.log(process.env.JWTPRIVATEKEY);
const userToken = jwt.verify(token, process.env.JWTPRIVATEKEY);
console.log(userToken.payload._id);
const user = await User.find({ _id: userToken.payload._id });
return user;
};
it("with success", async () => {
const question = {
title: "title",
content: "content",
};
const result = await request(app).post("/api/forum/question").set("Cookie", TOKEN).send(question);
console.log(result.body);
expect(result.status).toBe(200);
});
And I had this error:
{ error: { message: "Cannot read property '_id' of null" } }
I did change
const user = await User.findOne({ _id: userToken.payload._id });
by
const user = await User.find({ _id: userToken.payload._id });
And now it works as expected.
If someone can explain me why findOne was not working with test (but was ok with postman) I would be happy to understand... because to me, as beginner, it does not make any sense.
I'm working on an e-commerce web app using Laravel and Vuejs. I chose Stripe's API to accept and manage payments.
In my Vue component, which contains the payment form, and before making it visible(I'm using a multi-step form), I send a post request to my payments store controller function to 'initialize' Stripe and get the clientSecret variable. As follows:
axios
.post('http://127.0.0.1:8000/payments', {
headers: {
'content-type': 'multipart/form-data'
},
'total': this.total,
'mode_payment': this.mode_payment
})
This is how the store function looks like in my PaymentController:
public function store(Request $request)
{
$payment = new Payment;
$payment->montant_payment = $request->total;
$payment->mode = $request->mode_payment;
$payment->date_payment = Carbon::now();
$payment->statut_payment = false;
$payment->save();
Stripe::setApiKey(env('STRIPE_SECRET'));
header('Content-Type: application/json');
$intent = PaymentIntent::create([
'amount' => $payment->montant_payment,
'currency' => 'usd',
]);
$clientSecret = Arr::get($intent, 'client_secret');
$amount = $payment->montant_payment;
return response()->json($clientSecret);
}
As you can see, the store function sends back a JSON response containing the clientSecret variable. This response is then captured by the same Vue component discussed above.
This is how the Vue component captures the response:
.then((response) => {
this.clientSecret = response.data;
var stripe =
Stripe('pk_test_51JL3DSLJetNHxQ3207t13nuwhCB1KPvUJJshapsOQATnZn79vA4wK3p9Hf2yi2uUXfXXWdAtLZGRepfJGvRnd7oI006Kw6rFTC');
document.querySelector("button").disabled = true;
var elements = stripe.elements();
var style = {
base: {
color: "#32325d",
}
};
this.card = elements.create("card", { style: style });
this.card.mount("#card-element");
this.card.on('change', ({error}) => {
let displayError = document.getElementById('card-error');
if (error) {
displayError.classList.add('alert', 'alert-warning');
displayError.textContent = error.message;
} else {
displayError.classList.remove('alert', 'alert-warning');
displayError.textContent = '';
}
});
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(ev) {
ev.preventDefault();
// If the client secret was rendered server-side as a data-secret attribute
// on the <form> element, you can retrieve it here by calling `form.dataset.secret`
stripe.confirmCardPayment(String(this.clientSecret), {
payment_method: {
card: this.card,
billing_details: {
name: "testan testo"
}
}
})
.then(function(result) {
if (result.error) {
// Show error to your customer (e.g., insufficient funds)
console.log(result.error.message);
}
else {
// The payment has been processed!
if (result.paymentIntent.status === 'succeeded') {
console.log(result.paymentIntent);
window.location.href = 'http://127.0.0.1:8000/payment-success/';
}
}
});
});
})
Using Vue web dev tools I checked that the clientSecret variable has been successfully passed from the laravel store controller function to the payment Vue component, thanks to the execution of the commmand : this.clientSecret = response.data;.
However, when clicking the pay button, I get the following error in my console:
Uncaught IntegrationError: Missing value for stripe.confirmCardPayment intent secret: value should be a client secret of the form ${id}_secret_${secret}.
at X ((index):1)
at Q ((index):1)
at lo ((index):1)
at (index):1
at (index):1
at e.<anonymous> ((index):1)
at e.confirmCardPayment ((index):1)
at HTMLFormElement.eval (ComLivPay.vue?5598:339)
I guess the problem then is in the next portion of code:
stripe.confirmCardPayment(String(this.clientSecret), {
payment_method: {
card: this.card,
billing_details: {
name: "testan testo"
}
}
})
EDIT:
Since the problem seems to arise from the string form of the this.clientSecret variable. Here's how it looks like in Vue dev tools:
I am using next js as a front-end and laravel as a back-end. and i want to call back-end (laravel) api from getServerSideProps() method. as shown below
export async function getServerSideProps(context) {
const response = await Axios.request({
url: 'http://localhost:8000/api/event',
method: 'get',
headers: {
Cookie: context.req.headers.cookie,
},
})
const events = response.events
console.log(response)
return {
props: { events },
}
}
so i have also set the cookie but i am getting response with message unauthenticated like below
I just wanted to say a huge THANK YOU to Riaz Kahn for his answer. After a lot of banging my face against a wall this was the answer. I'm going to post a working example of my getServerSideProps function for anyone arriving here in the future. The getUser({[configObject]}) function is just returning a promise from an axios.get('my-user/route', config) call. This is working properly in a Next 13 app using standard pages functionality (not using experimental app directory).
export const getServerSideProps = async (context: any) => {
const {req, res} = context;
try {
const {data: user} = await getUser({
headers: {...req.headers}
});
return {
props: {
fallback: {user}
}
}
} catch (e) {
res.writeHead(302, {Location: '/login'});
res.end();
}
}
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
I am still learning Angular JS and have this controller which is making two ajax requests to the lastfm api using different parameters. I want to know when each request has been finished, so that I can display a loading indicator for both requests. I have researched it and read about promises and the $q service but cant get my head around how to incorporate it into this. Is there a better way to set this up? and how can I know when each request is done. Thanks.
angular.module('lastfm')
.controller('ProfileCtrl', function ($scope, ajaxData, usersSharedInformation, $routeParams) {
var username = $routeParams.user;
//Get Recent tracks
ajaxData.get({
method: 'user.getrecenttracks',
api_key: 'key would go here',
limit: 20,
user: username,
format: 'json'
})
.then(function (response) {
//Check reponse for error message
if (response.data.message) {
$scope.error = response.data.message;
} else {
$scope.songs = response.data.recenttracks.track;
}
});
//Get user info
ajaxData.get({
method: 'user.getInfo',
api_key: 'key would go here',
limit: 20,
user: username,
format: 'json'
})
.then(function (response) {
//Check reponse for error message
if (response.data.message) {
$scope.error = response.data.message;
} else {
$scope.user = response.data.user;
}
});
});
I have this factory which handles all the requests
angular.module('lastfm')
.factory('ajaxData', function ($http, $q) {
return {
get: function (params) {
return $http.get('http://ws.audioscrobbler.com/2.0/', {
params : params
});
}
}
});
Quite easy using $q.all(). $http itself returns a promise and $q.all() won't resolve until an array of promises are resolved
var ajax1=ajaxData.get(....).then(....);
var ajax2=ajaxData.get(....).then(....);
$q.all([ajax1,ajax2]).then(function(){
/* all done, hide loader*/
})