nodejs 간단 한 데이터베이스 추가 삭제 인터페이스 작성
2128 단어 javascript 학습
const httpManager = require('http');
const mysql = require('mysql');
// const urlManager = require('url');
var express = require('express');
var app = express();
var bodyParser = require('body-parser')
//
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", ' 3.2.1');
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
//
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123456',
database: 'test'
})
// application/json
var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
//
app.get('/getData', function(req, res) {
res.status(200);
connection.query('SELECT * FROM User', function (error, results, fields) {
if (error)
throw error;
res.json(results);
console.log('results is:', results);
});
});
//get
app.get('/deleteData', function(req, res) {
res.status(200);
let id = req.query.id;
res.json(req.query);
connection.query('delete FROM User where id = ?', id ,function (error, results, fields) {
if (error)
throw error;
});
connection.end();
});
//post
app.post('/addData', urlencodedParser , function(req, res) {
res.status(200);
res.send(req.body);
});
//
var server = app.listen(8080, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
})