반응형

자바스크립트 json 데이터 서버로 보내는법

 

Node.js express 모듈과 fetch 방식을 사용하면

POST 방식으로 보낸 데이터를 처리하는 방법이 기존의 ajax, xhr과 차이가 있다

 

 

 

fetch API

xhr, ajax 방식과 유사한데 가장 최근에 생겼고 최근 추세는 fetch api를 사용하는 듯함

아래는 사용 예시와 적용해본 방법

 

 

 

 

HTML

 

<form method="post" action="/">
    <input type="text" name="user[name]">
    <input type="text" name="user[email]">
    <input type="submit" value="Submit">
</form>

 

Javascript

 

function postTest(){
  fetch('/', {
      method: 'POST',
      headers: {
          'Content-Type': 'application/json'
      },
      body: JSON.stringify({
          user: {
              name: "John",
              email: "john@example.com"
          }
      })
  });
}

 

Node.js Express v4.16 이후

 

// Parse URL-encoded bodies (as sent by HTML forms)
app.use(express.urlencoded());

// Parse JSON bodies (as sent by API clients)
app.use(express.json());

// Access the parse results as request.body
app.post('/', function(request, response){
    console.log(request.body.user.name);
    console.log(request.body.user.email);
});

 

 

 

 

자바스크립트 JSON 데이터 POST로 서버에 전달해본 사용예시

 

function register(){
	var menu = document.getElementById("menu").value;
	var price = document.getElementById("price").value;
	var pay = document.getElementById("pay").value;
	
    var obj={"menu":menu,"price":price,"pay":pay};
    
    //POST 데이터를 보낼 url - ex) localhost/register
	fetch('/register', {
		method: 'POST',
		headers: {
			'Content-Type': 'application/json'
		},
		body: JSON.stringify({
			data:obj			
		})
	});
}

이렇게하면 json 구조는 { data : {"menu": menu, "price": price, "pay": pay} }가 된다

 

 

app.post('/registerAddr',function(request, response){	
	var body = request.body;
	
	console.log('body : ' + body.data.menu);
    //input으로 받은 menu 값 출력 확인
});

클라이언트에서 보낸 menu의 값을 확인할 수 있다

 

 

 

 

 

출처 : 

https://stackoverflow.com/questions/4295782/how-to-process-post-data-in-node-js

 

How to process POST data in Node.js?

How do you extract form data (form[method="post"]) and file uploads sent from the HTTP POST method in Node.js? I've read the documentation, googled and found nothing. function (request, response)...

stackoverflow.com

 

반응형

+ Recent posts