[Nodejs] get, post방식 간단정리 + ajax + DB
뷰엔진을 사용안했을 때
import express from "express"; const app = express(); // express import bodyParser from "body-parser"; // var bodyParser = require('body-parser') //서버구동 app.listen(3000, function() { console.log("express server start on port 3000"); }); //app.use 사용 //static 디렉토리 설정 //public이란 디렉토리에 html(뷰)만들었을 경우 자동으로 해당위치의 url로 접근하면 해당파일을 띄워줌(일일히 매매번 url 설정 귀찮을을때 유용) app.use(express.static('public')) app.use(bodyParser.json({extended: true})); //사용자가 웹사이트로 전달하는 정보들을 검사하는 미들웨어 app.use(bodyParser.urlencoded({extended: true})); //json이 아닌 post형식으로올때 파서 //get방식 (위에 static 디렉토리도 설정했으므로 이 밑 코드가없어도 해당 url로 접근하면 뷰를 띄워줄수는 있다. //하지만 다른 로직 작성 불가 app.get('/', function(req, res){ //get res.sendFile(__dirname + '/public/main.html') //해당 main.html띄워줌 }); //get방식 app.get('/main', function(req,res){ res.sendFile(__dirname + '/public/main.html') }); //post방식 app.post('/email_post', function(req, res){ console.log(req.body.email) //bodyParser 모듈 사용한 예, post방식으로 보낸 body에서 email 값 추출가능 res.send("hello " +req.body.email + "") //화면에 출력 }
(권장)
EJS 뷰템플릿엔진 사용했을 때 ,또는 pug도 있음
1. 설치방법 npm install ejs --save //// npm install pug --save
둘다 설치만 다르지 사용방법은 비슷한 것 같으므로 처음 배웠던 pug를 이용하도록 하겠음.
2. app.set("view engine", "pug"); //pug는 뷰엔진이다.
3. 뷰파일 생성할때 확장자 .ejs , .pug 붙이면됨
동적으로 바뀔것은 <% = email %> 이런식으로함 pug에서는 #{email}
또한 pug는 밑과 같이 태그 생략가능
doctype html html head link(rel="stylesheet", href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU", crossorigin="anonymous") title #{pageTitle} | #{siteName} body include ../partials/header main block content
뷰엔진을 사용해서 sendFile이 아닌 render()를 통해 데이터와 html을 결합한 상태로 클라이언트에 보여줄 때 사용할때 필요하다.
마지막으로 뷰엔진을 사용한 render는 다음과같다. (email 값을 전달해줘서 html과 전달해준 데이터를 결합해서 뷰를 띄워준다.
+)여기서 __dirname은 현재경로를 의미한다.
email_post로 전송하는 form
ajax처리
ajax요청 처리
데이터베이스 연결 (참고 => 프로젝트에 mysql이 설치된 상태이고 jsman데이터베이스에 email컬럼을 가진 user테이블을 만들어둔 상태다)
노드에 mysql을 사용할려면 npm install mysql --save
view
요청처리
다른 언어와비슷하다. 쿼리문을 작성후 rows로 해당컬럼을 갖고올 수 있다. 그리고 json형태로 응답을 보내준다.
출처 및 참고 : https://www.inflearn.com/course/node-js-%EC%9B%B9%EA%B0%9C%EB%B0%9C/lecture/6124
from http://youngest-programming.tistory.com/114 by ccl(S) rewrite - 2020-03-06 09:20:36
댓글
댓글 쓰기