Tuesday, 2 May 2017

nodejs + express + angular2 and invalid http response

latelly im facing a problem for a few days now..the thing is that i dont know what is wrong (although,i know its something that im doing wrong). lets go, im trying to create a angular2 + node + express + mysql. THe problem is when a try to get some response from the mysql in the front end. The error occurs when i try to submit the form in cadastrocomponent.js

the response that im get is:
    [![error from the request][1]][1]  

code

server.js

   var http = require('http')
    ,app = require('./config/express')
    db = require('./config/database');

port = process.env.PORT || 3000;

http.createServer(app).listen(port, function() {
    console.log('Servidor estutando na porta: ' + this.address().port);
});

database.js

var db = require('mysql');
var connection = db.createConnection({
        host: 'localhost',
        port:'3306',
        user: 'root',
        password: "",
        database: 'acoes'
});

connection.connect(function(err){
  if(err){
    console.log('Error connecting to Db');
    return;
  }
  console.log('banco escutando na porta ' +  +' Connection established');

});

module.exports.findall = function(callback){
  connection.query("SELECT * FROM users ORDER BY id DESC", callback);
}

/*if(!db) {
    db = new Datastore({
        filename: dbName, 
        autoload: true 
    });
    console.log('Banco ' + dbName + ' pronto para uso')
}*/


/*connection.end(function(err) {
  // The connection is terminated gracefully
  // Ensures all previously enqueued queries are still
  // before sending a COM_QUIT packet to the MySQL server.
});*/



module.exports = connection;

express.js

var express = require('express')
    ,app = express()
    ,bodyParser = require('body-parser')
    ,routes = require('../app/routes')
    ,path =  require('path');

app.set('clientPath', path.join(__dirname, '../..', 'client'));
console.log(app.get('clientPath'));
app.use(express.static(app.get('clientPath')));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());


app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  if ('OPTIONS' == req.method) {
      res.sendStatus(200);
  }
  else {
     next();
  }
});

routes(app);

module.exports = app;

routes.js

var api = require('../api'),
    path = require('path'),

user = require('../../config/database');

module.exports  = function(app) {


    app.route('/v1/lista', function(req , res){
            user.findAll(function(err, rows, fields){
                if(err) throw err;
                res.json(rows);

            })

    });


    app.route('/v1/fotos')
        .post(api.adiciona)
        .get(api.lista);

    app.route('/v1/fotos/:fotoId')
        .delete(api.remove)
        .get(api.busca)
        .put(api.atualiza);

    app.get('/v1/grupos', api.listaGrupos);
    app.get('/v1/fotos/grupo/:grupoId', api.listaPorGrupo);
};

myservice.js

  import {Http,Headers, Response} from '@angular/http';
import {Observable} from 'rxjs';
import { Injectable } from '@angular/core';

@Injectable()
export class MyserviceService {


http: Http;
headers:Headers;

url:string = 'http://localhost:3306/';
resposta =  ["Saab", "Volvo", "BMW"];

  constructor(http:Http) { 
    this.http = http;
    this.headers = new Headers();
     this.headers.append('Content-Type', ' text/html');

  }


getUsers() {
        return this.http.get('http://localhost:3306/');
    }

lista(){
      let end = this.url.concat("adduser");
      console.log(end);
    return this.http
    .get(end);
    //.map(res => res.json());

}
}

cadastrocomponent.js

<h3 class="text-center">Cadastro de Açoes</h3>

<h4>
    <div class="container">

         <!--colocar placehoder nos inputs     -->
        <form #meuForm="ngForm" class="row" (submit)="listar($event)">
            <div class="col-md-6">
                <div class="form-group">
                    <label>Título</label>
                    <input name="nome" #titulo="ngModel"  [(ngModel)]="nome"
                     required class="form-control"  autocomplete="off"
                     placeholder="insira o código da açao">    
                </div>

                <div class="form-group">
                    <label>Data Compra</label>
                    <input type="date" (keyup)="0" [(ngModel)]="dataCompra" name="{dataCompra}"
                     required class="form-control"  autocomplete="on" 
                     placeholder="dia/mes/ano" useValueAsDate>

                    <label>Descrição</label>
                    <textarea name="descricao" [(ngModel)]="descricao" class="form-control"  autocomplete="off"
                    placeholder="descriçao da açao">
                    </textarea>
                </div>

                <button type="submit" class="btn btn-primary" [disabled]="meuForm.form.invalid" >
                    Salvar
                </button>
                <a [routerLink]="['/acao']" class="btn btn-primary">Voltar</a>
            <hr>
            </div>
        </form>
    </div>
</h4>

i know that is something i have misplaced...but dont know what. any help?



via tecnocrata

No comments:

Post a Comment