jcramalho

Servidor da aplicação myPara

Nov 13th, 2017
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Servidor nodejs do myPara
  2. var http = require('http')
  3. var fs = require('fs')
  4. var qs = require('querystring')
  5.  
  6. var myserver = http.createServer(function(req, res){
  7.     console.log('Recebi um pedido: '+ req.method)
  8.     if(req.method === "GET"){
  9.         console.log('Recebi um pedido da paraBD...')
  10.         fs.readFile('paraBD.json', 'utf8', function(err, data){
  11.             if(!err){
  12.                 res.writeHead(200, {'Content-Type': 'application/json',
  13.                                     'Access-Control-Allow-Origin': '*'})
  14.                 res.write(data)
  15.                 res.end()
  16.             }
  17.             else{
  18.                 console.log('Erro na leitura da BD.')
  19.                 res.writeHead(404, {'Content-Type': 'text/plain'})
  20.                 res.end('Erro ao ler a BD.')
  21.             }
  22.         })
  23.     }
  24.     else {  // tratamento de pedidos POST
  25.         var requestBody = ''
  26.         req.on('data', function(data){
  27.             requestBody += data
  28.         })
  29.         req.on('end', function(){
  30.             var sentData = qs.parse(requestBody)
  31.             var paras = []
  32.             fs.readFile('paraBD.json', 'utf8', function(err, data){
  33.                 if(!err){
  34.                     paras = JSON.parse(data)
  35.                     paras.push(sentData)
  36.                     console.log('Vou gravar o para: ' + JSON.stringify(sentData))
  37.                     fs.writeFile('paraBD.json', JSON.stringify(paras), function(err){
  38.                         if(!err){
  39.                             res.writeHead(200, {'Content-Type': 'text/plain',
  40.                                                 'Access-Control-Allow-Origin': '*'})
  41.                             res.write('Parágrafo guardado: ' + JSON.stringify(sentData))
  42.                             res.end()
  43.                         }
  44.                         else{
  45.                             res.writeHead(200, {'Content-Type': 'text/plain',
  46.                                                 'Access-Control-Allow-Origin': '*'})
  47.                             res.end('Erro ao escrever a BD.')
  48.                         }
  49.                     })
  50.                 }
  51.                 else{
  52.                     console.log('Erro na leitura da BD.')
  53.                     res.writeHead(404, {'Content-Type': 'text/plain'})
  54.                     res.end('Erro ao ler a BD.')
  55.                 }
  56.             })
  57.         })
  58.     }
  59.    
  60. })
  61.  
  62. myserver.listen(7777)
  63. console.log('Servidor à escuta na porta 7777...')
Advertisement
Add Comment
Please, Sign In to add comment