인디노트

Angular, Nodejs 용 Ajax 샘플 코드 본문

개발 플랫폼 및 언어/노드 Node & NPM

Angular, Nodejs 용 Ajax 샘플 코드

인디개발자 2023. 4. 21. 07:48
// 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);
        }
      );
  }
}
반응형
Comments