How to pass data from AngularJS frontend to Nodejs backend using PostgreSQL? - javascript

Ready login page and register page using HTML and AngularJS. I have connected database PostgreSQL, but I don't know how to pass data from AngularJS frontend to Nodejs backend using PostgreSQL.

You can do it by several ways like using
"$http" - https://docs.angularjs.org/api/ng/service/$http
or
"ngResource" - https://docs.angularjs.org/api/ngResource/service/$resource
Using these you can pass data to Node.js backend(I assume "Express.js"). Since DB data will be executed by backend you just need to post your login or registration values to back-end. Here is below is a simple $http process:
$http.post('/login', {
email: this.email,
password: this.password
})
.success(function(response){
// execute your response
});
Actually for login/registration and another security purpose I recommend using JSON Web Token (JWT). https://jwt.io/introduction/

Related

API authenticate to odoo with token

I want to authenticate to Odoo from an express application using token. I am using odoo-xmlrpc node module to connect Odoo with
my express app. Odoo requires users of the API to be authenticated before they can use any other API. And this node module provides this function
const odoo = new Odoo({
url: config.odooUrl,//odoo url
db: config.odooDB,//odoo db path
username: "john#gmail.com",
password: "john_pass123"
});
odoo.connect(function(err, uid) {
if (err) {
errors.auth = "invalid cridentials";
return res.status(400).send(errors);
}
//execute something from/to odoo server
})
The problem is, I have to enter the user's credentials every time I want to execute an Odoo command. And if I store the user's password it would be stored as a plain text.
My question is, is their token-based authentication to Odoo that can be used through API. Or any other alternative solution to my problem
Currently in Odoo unfortunatelly there is no good solution to this. There is work in progress for support for api token access and 2-factor authentication in this pull request: https://github.com/odoo/odoo/pull/33928.
There are also multiple Odoo rest api modules in app store that support token authentication. You can find these with seach ”rest api” or ”token”. To me none of these have been perfect for my use-cases. I look forward to get native support for this in Odoo Community.

ReactJS - Handle POST requests using react router dom

Is there a way to handle POST requests using the react-router-dom (npm) library?
Why? The payment gateway will redirect the user, who successfully payed, back to the platform. I can use a GET or POST request to transfer data with the redirection page. But I don't like having the data visible in the URL. Other options are always welcome, I'm using a REST API (Node.JS, Express) and a website/dashboard (ReactJS)
I get what you're after but you can't POST to the browser. If you're uncomfortable passing data as GET params in a URL, you could:
store data in LocalStorage when user submits
deliver server-rendered, static HTML upon redirect that contains purchase information
asynchronously get user's purchase data upon page load with AJAX or fetch() (or your favorite data-grabbing util).
Since you're in a React world, I'd recommend the third option here. How to fetch data, build an API endpoint, store data, then display it goes well beyond the scope of this question so I'd suggest some Googling. Here's a starting point: https://code.tutsplus.com/tutorials/introduction-to-api-calls-with-react-and-axios--cms-21027
You can handle the POST request on your express server then redirect to a static page of your app :
app.post('/payment_webhook', (req, res) => {
const paymentOk = req.body.payment // handle POST data
if (paymentOk) {
res.redirect('http://app.com/payment_success');
} else {
res.redirect('http://app.com/payment_failed');
}
});
I was discussing the same with a friend and so far we saw 2 ways of doing this:
let the payment gateway return_url be an endpoint of the backend API (rails api), which will do the commit to the payment gateway (and probably updating the order in the BD), and then it will do a redirect back to your frontend app
store the gateway trasaction token on the order object in the DB, and let the payment gateway return_url to return to a dynamic order url, therefore, react will now which order should render, then asynchronously ask the backend (rails service) to extract the token from the order object and do the commit (confirmation) and update it's status and return the order object back to react, then react can now show if the order was successful or not.
we opted for option #2, since I feel that the frontend (react) shall be the main communication gateway to our system, and the only one communicating to the backend shall be the frontend.
UPDATE: option #2 did not work since you cant do POST to a react-app therefore, we make the return_url to be dynamic, and we immediately redirect to the frontend with a url with the order_id as query param, then, the frontend when tries to load the order, in the backend we do the payment gatway confirmation, update the order object and return the updated order object to the frontend

Simple connection to mongodb in react app

I have created simple react app using 'create-react-app'. This app contains form, validation and bootstrap things. Nothing fancy yet works like a charm.
I have also signed up to mongo to get a free cluster so I can send over some data to. So I have this URL:
mongodb+srv://matt:passwprd#cluster0-jlasm.mongodb.net/test
Now, all I want to do is to send JSON data from the form to mongo but I don't know how.
When I am following tutorials and installing MongoDB, mongoose or whatever packages and adding basic setup for future CRUD operations:
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb+srv://mattOsuch:brainhub123#cluster0-jlasm.mongodb.net/test';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
db.close();
});
The entire application crashes:
./node_modules/mongodb-core/lib/uri_parser.js
Module not found: Can't resolve 'dns' in 'C:\Users\Mateusz\Desktop\brainhub\node_modules\mongodb-core\lib'
I used to send data using jQuery or mysql_query in PHP but I can't overcome this problem. In other words I want to achieve functionality like presented in this video: https://www.youtube.com/watch?v=Jsqz5op4fH8 So as I said, simple data update.
My suspicion is that react-scripts server listener has some sort of conflict with mongo but I am not sure.
Please help me because I am loosing my nerves.
You are using node.js so start server app try using express routing here is a link to a tutorial https://zellwk.com/blog/crud-express-mongodb or https://codeburst.io/hitchhikers-guide-to-back-end-development-with-examples-3f97c70e0073 or try doing a google search(node.js mongodb and express).
Then when returning a request from server send the data required then use your react client to handle the data recived
Hope it works!
handleSubmit(){
let databody = {
"name": this.state.name,
// Remaining form Data
}
return fetch('mongodb+srv://mattOsuch:brainhub123#cluster0-jlasm.mongodb.net/test', {
method: 'POST',
body: JSON.stringify(databody),
headers: {
'Content-Type': 'application/json'
},
})
.then(res => res.json())
.then(data => console.log(data));
}
render(){
return (
<div>
<form onSubmit={this.handleSubmit}>
// Form Fields
<input type="submit" value="Save" />
</form>
</div>
);
}
To connect to MongoDb in javascript, you must use a node.js server.
It is therefore impossible to directly connect your React application to your MongoDb cluster.
For more information, visit the official MongoDb documentation
First you need to create a React.js on the frontend and then node.js on the backend web application.
Then, you need to connect your mongodb collection to your Node.js server.
Then you can send your form data to your node.js server and your node.js server will send your form data to your mongodb collection.
Making a full-stack React-NodeJS-MongoDB web application can be a little challenging, if you do not know NodeJS. So you might first start with EJS-NodeJS-MongoDB web application. But in any case, here are links for your question:
https://www.youtube.com/watch?v=3isCTSUdXaQ&t=2248s
https://www.youtube.com/watch?v=Oa0pMn0tvU4&t=1316s

How to handle API credentials in an Angular app?

I created an API in Laravel and I have a small SPA in Angular that logins in the app via an username & password and receive a token. With this token you can do some basic stuff with the API.
It's not ok to save the credentials (user&pass) in the Angular app (plain text - javascript etc etc). How can I handle this kind of auth in Javascript? What is a best practice?
After login, You can return the token and store in a localstorage for future use and refresh, and if you don't want put your token in every ajax call manually you can add to $http like:
$http.defaults.headers.common['Authorization'] = 'Bearer ' + storage.token;
I have tried this with angularjs and laravel with this library:
https://github.com/tymondesigns/jwt-auth

How to create users in Django's backend database when using Vue.js and Auth0 for frontend authentication

I am trying to use Vue.js as a frontend, and Django as the backend for an SPA.
In the frontend, I am leveraging Auth0 for user authentication and I want to send the id_token obtained from user registration/creation from Auth0 to the backend to create specific user profiles in real-time.
How do I create user profiles on my django backend for every user when they register using Auth0 on vue.js on the frontend?
Previously, I was using the following code to enable profile creation once a user is created:
# Whenever a User account is created, it creates a profile for it too.
def create_profile(sender, **kwargs):
user = kwargs["instance"]
if kwargs["created"]:
user_profile = UserProfile(user=user)
user_profile.save()
post_save.connect(create_profile, sender=User)
def __str__(self):
return self.user.username
In simpler terms, this is what I am trying to achieve:
- User registers on the website
- Account is created by leveraging Auth0
- user_id from Auth0 is fetched and sent to the backend (Django) from the frontend (Vue.js)
- Django creates a user profile for the registered user in its backend postgresql database.
- User is now able to access his profile page http://website/profile once logged in. (Data for the profile is fetched from Django)
I am fairly new to Vue.js and Javascript. Although Vue.js is a breeze to use, but I can't seem to figure out how to replicate similar functionality in Vue.js with Auth0.
Any help/guidance/pointers in the right direction are appreciated.
Thanks.
You want to make Ajax calls - I recommend Axios - to communicate between your client and server sides. It's pretty straightforward, I've been using it with Vue.js & love it.
Something like:
in auth.vue:
axios.post('/yourUserRoute', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
If you make sure that you call this axios call every time you want to register a new user, your back-end will receive the correct informations for you to proceed on your server. I never touched Django so I'm not going to try and help you on the details, but this should give you a good start to work with!

Categories