I started creating a new application using Laravel and Nuxt Js.
i have two VPS servers :
The first one contain my Nuxt JS ( Front End )
The second one is the end point ( back end ) based on Laravel
i have created a lot of pages i insert the data correctly into my database. and now i tried to create a new function to update users data, but i get an error after submiting the form since i use the same axios code to insert.
Right now i'm working without tokens and i know its insecure way.
i would like to know how can i communicate the tokens between Nuxt JS front end Laravel Backend.
i have two servers.
the error that i get is :
CSRF token mismatch.", exception: "Symfony\Component\HttpKernel\Exception\HttpException
this is my Axios code :
edit (customerId, submit = false) {
this.editMode = true
this.customerId = customerId
if (submit === 1) {
const formData = $('#add-customer').serialize()
this.$axios.$post('/customer/update', formData).then((response) => {
this.refresh = true
})
} else {
this.$axios.$get('/customer/edit?customer=' + customerId).then((response) => {
this.formFields = response.data[0]
})
}
}
when i change this line from post to get, it works fine
this.$axios.$post('/customer/update', formData)
I would suggest using a single Redis server for session management,so you have a centralized location. or using a database, for more details check laravel doc
https://laravel.com/docs/6.x/session
Related
I have written a simple todo app with react acting as a frontend and flask handling CRUD from a DB. The app is using axios to handle the requests; GET completes fine however when attempting to POST JSON the flask api returns a 400 error. Here's some condensed sample code.
JS POST function.
function testPost(){
axios.post('http://'+window.location.hostname+':8000/todo/', {
title: "test123",
}).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
}
Serverside
class Todo(Resource):
def post(self): # create a new todo
conn = pool.getconn()
cur = conn.cursor()
app.logger.info(request.form['title'])
cur.execute("INSERT INTO todo (task, done) VALUES (%s, %s)", (request.form['title'], False))
conn.commit()
app.logger.error(e)
cur.close()
pool.putconn(conn)
Other methods not shown
Then the rest of the server code attaching the resource to the api and the CORS setup (not shown in file order)
app = Flask(__name__)
CORS(app, methods=['POST','GET','PUT','DELETE'])
api = Api(app)
api.add_resource(Todo, '/todo/')
app.run(debug = True, host='0.0.0.0', port=port)
Tests
Using python to test the api works fine, running this in a seperate python file will add to the DB.
response = requests.post(URL + "todo/", data={"title": f"test{randint(1, 100)}"})
My best guess is that axios is not adding the data to the request in a way that the backend is unable to process. Before using axios I tried to make the request with XMLHttprequest however this presented the same problem. I swapped to axios on the recommendation of someone else, given its alleged improved simplicity.
request.form['key'] and request.get_json()['key'] are completely different fields python requests in the way I used it posts to the former and js posts to the latter. Modifying the function to use whichever is available fixes this.
I'm developing a Laravel + Angular app and i'm getting 401 Unauthorized in only 1 GET request.
Here I explain how I developed my authentication and how it work on Backend and Frontend. I wish you can help me.
I use Laravel Sanctum for manage authentication in my app. Here is how I program the backend.
I get users from my BD table:
Note: I have created a separate controller, to separate the authentication functions from the user functions, even so, I have tried to put this function in my AuthController and it has not given me any result.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UsersController extends Controller
{
public function getAllUsers()
{
return User::all();
}
}
As I want you to only be able to retrieve all the DB users if you are authenticated, in my api.php file I put the path inside the middleware:
Route::middleware('auth:sanctum')->group(function()
{
Route::post('logout', [\App\Http\Controllers\AuthController::class, 'logout']);
Route::get('getAuthUser', [\App\Http\Controllers\AuthController::class, 'getAuthUser']);
//Admin actions
Route::post('createUser', [\App\Http\Controllers\AuthController::class, 'createUser']);
Route::get('getAllUsers', [\App\Http\Controllers\UsersController::class, 'getAllUsers']);
});
If I make the request from the Postman everything works correctly, if I am not authenticated it gives me an error and if I have previously authenticated it returns all the DB users just as I expected. By the way, I am using cookies to send the jwt to the Frontend.
The problem is when in my Angular app I request my backend with the GET method to retrieve these users and display them in a table. In addition, the code to retrieve the users is within a condition in which it is looking at whether the user is authenticated or not. The truth is that I do not understand what may be happening.
getUsers(): void
{
//Check if user is authenticated
this.http.get('http://localhost:8000/api/getAuthUser', { withCredentials: true }). subscribe(
(res: any) =>
{
Emitters.authEmitter.emit(true);
Emitters.roleEmitter.emit(res.role);
//Get all users
this.http.get('http://127.0.0.1:8000/api/getAllUsers', { withCredentials: true }). subscribe(
res =>
{
this.users = res;
}
)
},
err =>
{
Emitters.authEmitter.emit(false);
Emitters.roleEmitter.emit("none");
alert("You should be authenticated for this.");
}
);
}
The first request that you see above getAuthUser, makes the request to the Backend in the same way as the second request getAllUsers and the first one works perfectly and the second one does not, it is in which I get an err. I call the getUsers() method in the ngInit().
I hope I have explained myself well. Any information you need to know let me know. Thank you.
The solution was in the request that gave the error to change the path of the api, instead of putting 127.0.0.1 putting localhost.
I'm developing an app with node and react. In this app, I have created a scriptTag using the fetch function to get customer id and product id whenever a specific button is pressed. Now when I have fetched that data, I want to store it in my firebase database, which I cannot import in my script tag file because it's on the front end. Therefore, I need to send the data from my frontend to the backend of the app but I'm confused that if I use the fetch function to make POST and GET requests, what URL should I use? Moreover, can the fetch function even post the variable values or not?
Scripttag.js
const header = $('header.site-header').parent();
header.prepend('<div>Hello this is coming from the public folder </div>').css({'background-color':'orange', 'text-align': 'center'})
function addWishList(customer, productid){
/*
fetch(`url`, {
method: 'POST',
headers: {
'Content-Type': ,
"X-Shopify-Access-Token": ,
},
body:
}})
})
*/
console.log('adding item to the wishlist!!')
}
function removeWishList(){
console.log('removing item from the wishlist!!')
}
var wishbtn = document.querySelector('.wishlist-btn')
wishbtn.addEventListener('click', function(){
if(this.classList.contains('active')){ //condition to check if the button is already pressed
removeWishList();
this.classList.remove('active');
this.innerHTML = 'Add to wishlist'
}
else{
var customer = wishbtn.dataset.customer;
if(customer == null || customer == ''){
console.log('Please log in to add this item to your wishlist')
}
else{
var productid = wishbtn.dataset.product;
this.classList.add('active'); //when the user presses add to wishlist button, it add active to the button's class
this.innerHTML = 'Remove from wishlist'
addWishList(customer, productid);
}
}
})
The best way to send data from the frontend to the backend is to use the Proxy option that is provided in the Shopify Partner Dashboard.
This way you can stay in the Shopify environment since it will pass specific arguments to the request that you can check if the request is truly coming from Shopify and you will have one less worry about securing it from outside requests.
So for example you will make a fetch request to /apps/YOUR_CUSTOM_PATH and this will proxy to your URL https://example.com/custom_path where you will handle the request.
You can see more info here: https://shopify.dev/tutorials/display-data-on-an-online-store-with-an-application-proxy-app-extension
You can create a public route for your app as well that can be requested from everywhere and allow for CORS but it's usually more work to do so... so pick your poison.
Have in mind that when creating a proxy page you need to reinstall the app on the store to take effect.
PS: Don't ever use the Access Token in the frontend, that should be never present in the frontend. The AccessToken is only back-end way of communicating with the API!
I am trying to post form data from angular to node.js. The angular post request sends an empty body.
this is my post router
submit function is ts file
onSubmit( loginData ) {
if(!loginData) { return; }
this.userService.addUser( loginData as User )
.subscribe(user => {
this.users.push(user);
});
service used to post data
addUser(user: User): Observable<User> {
// console.log('this is '+user.email);
const url = `${this.usersUrl}/register`;
return this.http.post<User>(url, user).pipe(
tap((newUser: User) => this.log(`added user w/ email=${newUser.email}`)),
catchError(this.handleError<User>('addUser'))
);
}
Please check once by adding the debug whether the loginData is getting passed in the service or not.
If you don't know how to add debug point simply just print the data using console.log(user)
in the method addUser() as the first line.
And if not getting data then simply modify the method call by:
this.userService.addUser(loginData).subscribe(user => {
this.users.push(user);
});
I figured out the problem.
There is no problem in this angular code.
I also checked the network tab as suggested by David, and saw that the payload was being sent.
the problem was this line of code in my node.js server
app.use(express.static('public'))
Instead I had to use
app.use(exrpess.json())
I had copied the template from another application and somehow missed this. Anyway thanks for all your help!
The scenario is payment gateway post some payment data to url '/payment-check'. On successful verification, I redirect the user to a particular url and set the header to be accessed by the angular client later.
Now the problem is headers are set in the post method and from angular, I can't make post method because payment gateway is posting data.
I also don't have payment data in the get method(express server) to send to the angular client.
Now how can I get set headers(payment data) in angular?
Or is there any alternative / easier way to achieve it.
One of the ways to do is querystring. But as payment_data is sensitive it is not a good idea to expose it in url
Here is my code
express.js file
router.post('/payment-check', function(req,res ) {
var options = req.body
console.log(options)
let secret ='XXXXXXXXX'
console.log(options.razorpay_order_id + "|" + options.razorpay_payment_id, secret)
if(// verification code) {
console.log("matched")
var payment_id = options.razorpay_payment_id
res.setHeader('payment_id' ,payment_id)
res.redirect('http://localhost:8100/menu/items/carts/payment-options/netbanking/order-success')
}
})
angular service
getPayemnt_id(): Observable<any> {
return this.http.get<any>(this.url + 'payment-check')
}
.ts page
this.serivename.getPayemnt_id().subscribe(data =>{
console.log(data)
})