일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
Tags
- Xcode
- SSH
- apple
- WebAuthn
- css
- OTP
- otpkey
- OSX
- albumbook
- fido
- SwiftUI
- SSL
- 애플
- MSYS2
- kmip
- 인증
- 앨범북
- 앱스토어
- FIDO2
- appres
- 앱리소스
- 2FA
- MFA
- MYSQL
- git
- openssl
- Nodejs
- SWIFT
- Android
- 안드로이드
Archives
- Today
- Total
인디노트
Angular, Nodejs 용 Ajax 샘플 코드 본문
// server.js
const express = require('express');
const app = express();
// CORS (Cross-Origin Resource Sharing) 설정
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
next();
});
// POST 요청의 바디 파싱을 위한 미들웨어 설정
app.use(express.json());
// POST 요청 처리
app.post('/api/data', (req, res) => {
// 클라이언트에서 보내진 데이터 처리 로직
const data = req.body;
console.log('받은 데이터:', data);
// 응답 데이터 전송
res.json({ message: '데이터를 성공적으로 받았습니다.' });
});
// 서버를 3000번 포트에서 실행
app.listen(3000, () => {
console.log('서버가 3000번 포트에서 실행 중입니다.');
});
// app.component.ts
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
template: `
<div>
<h1>Node.js Ajax 예제</h1>
<button (click)="sendData()">데이터 보내기</button>
</div>
`
})
export class AppComponent {
constructor(private http: HttpClient) {}
sendData() {
const data = { name: 'John', age: 30 };
this.http.post('http://localhost:3000/api/data', data).subscribe(
response => {
console.log('응답 데이터:', response);
},
error => {
console.error('오류 발생:', error);
}
);
}
}
Angular 에서 subscribe 이 권장되지 않기 때문에 다음 코드로...
// app.component.ts
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
template: `
<div>
<h1>Node.js Ajax 예제</h1>
<button (click)="sendData()">데이터 보내기</button>
</div>
`
})
export class AppComponent {
constructor(private http: HttpClient) {}
async sendData() {
const data = { name: 'John', age: 30 };
try {
const response = await this.http.post('http://localhost:3000/api/data', data).toPromise();
console.log('응답 데이터:', response);
} catch (error) {
console.error('오류 발생:', error);
}
}
}
Angular 에서 toPromise 도 권장되지 않기 때문에 다음 코드로...
// app.component.ts
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { from } from 'rxjs';
import { map } from 'rxjs/operators';
@Component({
selector: 'app-root',
template: `
<div>
<h1>Node.js Ajax 예제</h1>
<button (click)="sendData()">데이터 보내기</button>
</div>
`
})
export class AppComponent {
constructor(private http: HttpClient) {}
sendData() {
const data = { name: 'John', age: 30 };
from(this.http.post('http://localhost:3000/api/data', data))
.pipe(
map(response => {
console.log('응답 데이터:', response);
})
)
.subscribe(
() => {},
error => {
console.error('오류 발생:', error);
}
);
}
}
반응형
'개발 플랫폼 및 언어 > 노드 Node & NPM' 카테고리의 다른 글
A simple guide to load C/C++ code into Node.js JavaScript Applications (0) | 2023.04.23 |
---|---|
nodejs 에서 NIC 정보 읽기 (0) | 2023.04.21 |
Node.js 용 c++ Addon을 gcc로 컴파일하기 (node-gyp 없이) (0) | 2021.06.27 |
node command line application 만드는 방법 (0) | 2020.12.25 |
require는 어떻게 동작할까? (0) | 2020.12.21 |
Comments