connection between angular and node - node.js

I have an angular app and I want to connect to node.js server. My question is how to do that? Do I have to write any code on my angular app to set the connection and then send the http request or just send the requests to the server? (I have all the API's ens points).
When I just send the request I get 404 error.
export class ApiConnectionService {
uri = "http://dev.cantinadigital.co.il:8080";
constructor(private http: HttpClient) { }
postContactUsMessage(message: Object): Observable<any> {
return this.http.post(${this.uri}/contactus, message);
}
}

If you have Angular app working for example on 'localhost:3000' and node server on 'localhost:5000' You have to send request to node server address. So if you want to get for example list of todo's you have to send 'GET' request to 'localhost:5000/todos'. But if it all works on one port, You just send request to '/todos' and that should work well.

You just send a request to your server.
For Example:
public doSomething(): Promise<any> {
var url = "localhost:8081/api/test";
return this.http.get(url, option).toPromise();
}
When you call the function, don't forget its asynchronous:
doSomething().then(result => ....)
Also you have to adjust your proxy settings, so you have to add an entry in proxy.conf.json
If you get a 404 maybe your server setup is not working. So maybe it would be best if you check with Postman, if you can reach your url.

I made a demo for you to how to deal with the Http calls and Api in angular and put you a comment in what you should change to work with your case:
https://stackblitz.com/edit/angular-service-intro?file=src%2Fapp%2Fapp.service.ts
Hope this helps you

Related

Post a simple react form - node, axios, nodemailer, backend, postman

I've set up a react form running on http://localhost:3000/about and I've the backend running on port 5000 (localhost:5000). On react's package.json I set up "proxy":"localhost:5000:.
When I use postman and I send the post to localhost:5000/api/contact, the email is sent correctly (I send the data as JSON - name, email and message). Status 200
When I use the react form, the data is well prepared as json but I can't figure out the baseURL to send correctly the method post. status 404. I tried:
localhost:3000/about/api/contact;
localhost:3000/api/contact;
localhost:3000/api.... None works...
FYI
the server is set up with the following middleware and is working ok:
app.use('/api',contactRoute)
the controller is imported and coded as following:
router.post('/contact', (req, res)=>{
const data = req.body;
The React part is not posting correctly with axios and is coded as following:
onSubmit: async (values) => {
//values.preventDefault();
try {
const data = (JSON.stringify(values, null, 2))
setLoader(true);
console.log(data)
await axios.post('/contact', data);
The method post in react is never completed, when I check the console.log of data, is correctly structured as JSON...status 404
use the post parameter in your axois request {port: 5000} then It will use your actual backend port.
By default, axios uses the base path from the URL. So, here when an API request is made.
await axios.post('/contact', data);
It is actually making the post request on localhost:3000 rather than your backend server at localhost:5000. Also, "api" should also be prepended.
One simple way is to use absolute URL which should work.
await axios.post('http://localhost:5000/api/contact', data);

How to use fetch to fetch data from AWS RDS in a react application?

I'm learning Node + React. In my Node + React application, I have the following component FetchData.js to fetch data from localhost:
import React from 'react';
class FetchData extends React.Component {
static async getData() {
let response = await fetch('http://localhost:4000/my-project');
let body = await response.json();
return body
}
}
export default FetchData;
I could see the json objects by typing localhost:4000 in the browser.
Now I'm hosting the data in AWS RDS. I have an endpoint like this:
my-project.abc12345def.eu-west-2.rds.amazonaws.com:3306
How can I fetch data from the endpoint like what I did in FetchData.js? I tried to replace localhost with the endpoint url, no luck; tried to type the endpoint url in a browser, could not see its content. I suppose I need to be able to see its content to be able to fetch data?
I will give you most simple difference
Fetch is a way to access HTTP resources like http://localhost:4000/my-project.
Your RDS endpoint (Most probably MYSQL) does not run an HTTP server.
So these endpoints (Links) are different, and they are not for the same purpose.
Edit:
You could connect to RDS using a MYSQL client from your server running on http://localhost:4000 which then return the data to fetch request.

How to pass routing control from Node server to client?

Let's say this is the part where all routes are handled on a Node server with Angular front end. When the user enters the site URL, the server sends all the static files for the browser to render. However, I would like the client to handle certain routes instead of it going directly to the server.
For example, if I enter www.exemple.com/page2, a Get request is sent to the server but the route doesn't exist so the request just hangs there and ultimately resulting an error.
I want Angular to handle the routing instead of it going automatically to the server. I've only successfully got this to work on localhost where the Angular app is served from a different port than the one that the server listens to. Can anyone one tell me how to achieve this? Thanks a lot.
module.exports=function(app,dir){
app.use(express.json());
app.use(express.static(dir+'/dist/probeeshq'));
app.get('/',(req,res)=>{res.sendFile(path.join(dir));});
app.use('/auth', userAuth);
app.use('/api/me',userData);
app.use('/api/org',organization);
app.use('/api/messaging',messaging);
app.use('/api/search',search);
app.use(error);
}
This is what I have in Angular
const routes: Routes = [
{ path:'', component: HomeComponent },
{ path:'project_gaea', component:ProjectGaeaComponent},
{ path:'dashboard', component: DashboardComponent ,canActivate:[AuthGuardService]},
{ path:'explore', component:ExploreComponent, canActivate:[AuthGuardService]},
{ path:'create', component: CreateComponent },
{ path:'user/:id', component:UserProfileComponent},
{ path:'**', component: PageNotFoundComponent}
];
You can achieve this by implementing the Route feature that Angular has out of the box. After you implement this, you can then just use your back-end as an API.
So it turns out that I was supposed to serve the application like this:
app.use('/', express.static(dir));
And Express will let Angular handle all the routing after failing to match all the routes at the server side. dir is just the path were the Angular app is.
I have the same issue, with wildcard routes we can fix this. And client routes handling any unrecognised urls. Good from the user experience perspective no issues on that
like so
app.get("*", (req, res) => {
// send HTML files
});
But what about auditing wise, like a simple question like "if I send a unrecognised URL to server, it should give a 404 status code, instead of redirecting me to client and showing a 404 page or something"
Made a valid point, which doubted my knowledge on the web. But to resolve this we need to manually whitelist the client URL's in server, still figuring out myself, if any better solution please let me know.

How to enable POST method on heroku server (for React app)? I am getting 405 method not allowed

I am getting 405 method not allowed. I am using axios.post for login.
The form is taking input username and password and post to get authenticate.
But POST method not allowed at heroku error in console.
Please help me to let me know how to enable POST method on heroku. or any solution.
Thanks in advanceenter image description here
This is an axios post example:
axios.post("test/test", {userName:'..', password:'..'}).then((result) => onSuccess(result.data), (error) => onError(error));
If you are using spring-boot with Java you probably have a CORS problem. Try to put in your endpoint:
#CrossOrigin(origins = {"http://localhost:3000", "url2", "url3})
Replace "http://localhost:3000" with your localhost url if you need it. This is an example:
#CrossOrigin(origins = {"http://localhost:3000", "url2", "url3})
#RequestMapping(value = "/test", method = RequestMethod.POST)
ResponseEntity<HttpStatus> testLoginUser(#RequestBody DTO testDto) throws TestException {
//Do Something..
}
I don't know how the server is implemented, so: check if you have a CrossOrigin problem or if you have a security problem with your endpoints.

How to add facebook authentication to my react app?

I'm using express as backend. I implemented facebook authentication at the backend.
router.get('/login/facebook',
passport.authenticate('facebook',{scope:['email']}));
router.get('/login/facebook/callback',
passport.authenticate('facebook',{
successRedirect : '/home',
failureRedirect:'/'
})
);
Now I want to call this through my react app, so that when the user lands up at home page, first he should be authenticated by facebook then only he can see homepage. How can I do this ?
I tried using react-router, but I can't understand how to call backend using react-router.
I also fetched /login/facebook using fetch command :
componentDidMount(){
fetch("127.0.0.1:3001/login/facebook");
But it gave me CORS error.
My react app is at 127.0.0.1:3000 and express server at 127.0.0.1:3001.
If this issue is only in dev mode, then Daniel's answer is correct.
In any case, I recommend to avoid calling the :3001 api directly from the :3000 app. Here's what I would do.
I will edit the fetch call as follows,
componentDidMount(){
fetch("/login/facebook");
}
This call will be received by the backend which serves the react application.
Now there are three cases,
Case 1: Your file serving app will have a proxy method which can forward requests to an API. For example read it here
Case 2 This is my Recommended approach. I would simply write the authentication logic in the :3000 server and only use the :3001 API for handling business logic of the app.
Case 3: If you have a backend app (:3000), say written using expressJs, you can forward the request to the :3001 API. Here is a sample code for that,
client.send({
method: req.method,
path: req.url,
data: req.body,
params: req.params
}).then( (response) => {
// Something
}).catch( (err) => {
// Handle error
});
Here the client is a module which uses the request module to make HTTP calls.
You can implement the above call as an express middleware to use it for all HTTP calls.
There are several options:
If you are using webpack dev server, you can set up a proxy to your api. See here
You can temporary disable cors validation during development. See here

Resources