일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
- 2FA
- 인증
- apple
- MSYS2
- FIDO2
- css
- MFA
- albumbook
- 안드로이드
- appres
- OTP
- Android
- OSX
- 앱스토어
- SWIFT
- MYSQL
- WebAuthn
- SSL
- kmip
- 애플
- SSH
- git
- otpkey
- openssl
- SwiftUI
- fido
- Xcode
- Nodejs
- 앱리소스
- 앨범북
- Today
- Total
인디노트
How To Post Data From Angular To Node REST API 본문
출처 : https://codehandbook.org/post-data-from-angular-to-node-rest-api/
When you get started with Angular web application development, one of the common scenarios encountered is how to pass data from Angular to REST API. In this tutorial, you’ll learn how to post data from Angular to Node REST API.
Source code from this tutorial is available on GitHub.
Creating An Angular App From Scratch
Assuming that you have the angular-cli installed, create a new Angular app using the angular-cli.
// create new Angular project ng new angular-node
The above command will create the boiler plate code for the Angular application. Once you have the boiler plate code, navigate to the project directory and start the application.
cd angular-node npm start
Point your browser to http://localhost:4200 and you will have the application running.
You will have a RootComponent as the base component, so remove the existing default AppComponent by removing all the related files. You should have only app.module.tsfile in the src/app folder.
Create the RootComponent using the following clicommand.
// create angular component ng g component root
Here is how the app.module.ts file looks:
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RootComponent } from './root/root.component'; @NgModule({ declarations: [ RootComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [RootComponent] }) export class AppModule { }
In Angular you’ll be using the HttpClient module to make the API calls. So import the HttpClientModule in the app.module.ts and add it to the imports array.
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { RootComponent } from './root/root.component'; @NgModule({ declarations: [ RootComponent ], imports: [ BrowserModule, HttpClientModule ], providers: [], bootstrap: [RootComponent] }) export class AppModule { }
Create an Angular service which will handle the API calls for the RootComponent. Navigate to the src/app/root folder and create an Angular service.
cd src/app/root ng g service root
Import the HttpClient in the root.service.ts file and initialize it in the constructor. Create a method called getAPIData which will fetch some data from a URL. Here is how the root.service.ts file looks:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class RootService { constructor(private http: HttpClient) { } getAPIData(){ return this.http.get('https://jsonplaceholder.typicode.com/users') } }
Import the RootService in the RootComponent. In the ngOnInit method of the RootComponent subscribe to the getAPIData method. Here is how the root.component.ts file looks:
import { Component, OnInit } from '@angular/core'; import { RootService } from './root.service' @Component({ selector: 'app-root', templateUrl: './root.component.html', styleUrls: ['./root.component.css'] }) export class RootComponent implements OnInit { constructor(private rootService : RootService) { } ngOnInit() { this.rootService.getAPIData().subscribe((response)=>{ console.log('response is ', response) },(error) => { console.log('error is ', error) }) } }
Save the above changes and start the Angular application. Once the application has loaded, check the browser console and you will have the response from API call logged in the browser.
So, you were able to use HttpClient to make API calls from Angular application. Now, let’s start with creating a Node REST API endpoint and try to post data from Angular to Node REST API.
Creating a Node REST API
You’ll be making use of express, Node.js web application framework for creating the Node REST API endpoint.
Let’s get started by creating a folder called API. Inside API folder initialize a Node project using npm.
mkdir api cd api npm init
Press enter for the default fields and you’ll have the Node project initialized. Now, install express web framework using npm.
// install express framework npm install express --save
Once the express framework has been installed create a root file called app.js. Inside app.js require the express framework and create an express app. To start run the app you need to listen the app on a port. Here is how the code looks :
const express = require('express') const app = express() app.listen(3000, () => console.log('Example app listening on port 3000!'))
Save the changes and start the Node app using the following command:
// run Node app node app.js
You’ll have the app running at http://localhost:3000. But you’ll get an error if you try to browse http://localhost:3000/ since you haven’t defined a route handler yet.
Let’s define a default route handler / for the Node app.
const express = require('express') const app = express() app.get('/', (req, res) => { res.send('Welcome to Node API') }) app.listen(3000, () => console.log('Example app listening on port 3000!'))
Save the changes and restart the Node server. Point your browser to http://localhost:3000/ and you’ll have the message returned as response.
Now, let’s create a Node REST API endpoint with GET request which will return a JSON response. Here is how the API looks:
app.get('/getData', (req, res) => { res.json({'message': 'Hello World'}) })
Save the changes and restart the server. Point your browser to http://localhost:3000/getData and you’ll have the JSON data returned in browser.
{ "message": "Hello World" }
Let’s also create a Node REST API endpoint with POST request. You’ll be using the app.post to create a POST REST API endpoint. Here is how the code looks:
app.post('/postData', (req, res) => { })
You’ll be making use of the body-parser, a Node.js body parsing middleware to parse the posted parameters. Install body-parser using npm.
// install body parser middleware npm install body-parser
Once the body-parser has been installed require it in app.js.
// require the body-parser const bodyParser = require('body-parser')
Add the body-parser json middleware in the postDataNode REST API endpoint. Here is how the postData REST API endpoint looks:
app.post('/postData', bodyParser.json(), (req, res) => { res.json(req.body) })
After receiving the request at the postData endpoint, it’s returning the received request parameters as JSON response.
Save the above changes and restart the server. You’ll have both the GET and POST Node REST API endpoints ready to use.
Creating a Proxy From Angular to Node REST API
Angular application and the Node REST API endpoints are running on different ports. So you’ll need a proxy configurations to post data from Angular to Node REST API endpoint.
For configuring proxy in the Angular application, create a proxy file called proxy.conf.json inside the Angular application root. Here is how it looks:
{ "/api/*": { "target": "http://localhost:3000", "pathRewrite": {"^/api" : ""} } }
Modify the Angular app to start with proxy configuration using proxy.conf.json. Inside the package.json file modify the start script as shown:
"scripts": { "ng": "ng", "start": "ng serve --proxy-config proxy.conf.json", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e" }
Once you have started the Angular application, any requests starting with /api/ from the Angular application will be routed to the Node REST API server. Now, let’s see how to post data from Angular to Node REST API endpoint.
Post Data From Angular To Node REST API
Finally, let’s add the necessary code to make the API calls from the Angular application.
Inside the root.service.ts file, create a new method which returns the postData API call observable.
postAPIData(){ return this.http.post('/api/postData', {'firstName' : 'Code', 'lastName' : 'Handbook'}) }
Inside the RootComponent in root.component.ts file, subscribe to the postAPIData method in ngOnInit.
this.rootService.postAPIData().subscribe((response)=>{ console.log('response from post data is ', response); },(error)=>{ console.log('error during post is ', error) })
Save the above changes and restart the Angular application. Once the server has been restarted, point your browser to http://localhost:4200/ and check the browser console. You’ll have the post API response logged in the browser console.
Angular POST Response
Post Data From Angular To Node REST API
Wrapping It Up
In this tutorial, you saw how to post data from Angular to Node REST API endpoint. Along the course of this tutorial, you learnt how to set up a Node REST API endpoint, create an Angular proxy configurations for routing the API calls from Angular to Node REST API and how to make GET and POST API calls from Angular.
Source code from this tutorial is available on GitHub.
'개발 플랫폼 및 언어 > 앵귤러 Algular' 카테고리의 다른 글
Angular 에서 environment 값 가져오기 (0) | 2023.04.21 |
---|---|
Download Files with Axios (0) | 2021.01.22 |
Angular 에서 jquery, jquery.backstretch 사용하기 (2) | 2020.11.29 |
AngularJS 와 NodeJS 를 함께 가동하기 (0) | 2019.08.22 |
앨귤러 JS 시작하기에 필요한 설치 (0) | 2017.12.17 |