简体   繁体   中英

How to read data in node.js app.js from IONIC typescript through REST API?

My service.ts is like this :

import { Injectable } from '@angular/core';
import {Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map';

/*
  Generated class for the PeopleSearch provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
@Injectable()
export class PeopleSearch {
  data: {name:'morr', age: 19, email:'mor@mo.com' };
  apiurl: "http://localhost:3082";

  constructor(public http: Http) {
    console.log('Hello PeopleSearch Provider');

  }

  load1() {
    return new Promise(resolve => { 
      let headers = new Headers();

      this.http.post('http://localhost:3082/users/u/',JSON.stringify(this.data),{ headers: headers })
        .map(res => res.json())
        .subscribe(data => {
          //console.log(data.user1);


          resolve(data);
        });
    });
  }  

And my app.js is like this :

const express= require('express')
const app= express();
const morgan= require('morgan')
const mysql= require('mysql')
var cors = require('cors');
app.use(cors());

const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); 



const connection= mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'test'
})

app.use(morgan('combined'))


app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
    res.header("Access-Control-Allow-Methods", "GET, PUT, POST");
    if ('OPTIONS' === req.method) {
        res.status(204).send();
    }
    else {
        next();
    }
});
app.post("/users/u", (req, res) => {
    const name=req.body.name
    const age= req.body.age
    const email= req.body.email
    const querystring="insert into users values(?,?,?,?)"
    connection.query(querystring, [11,name,age,email],(err,results,fields)=>{
        console.log("success sql post")
        res.end()        
    })
  })

app.listen(3082, () => {
    console.log("Server is up and listening on 3082...")
  })

I am not getting where I am exactly wrong. If I write data hardcoded in all variables, username age and email, then post req is executing successfully. But when I am using req.body to get the data posted by typescript then i think Its not reading properly.

can anyone suggest what to use or how to use req.body to get the data in variables and save it in query??

You have not defined your data correctly in the PeopleSearch service. Take a close look at the top of the PeopleSearch class. This:

@Injectable()
export class PeopleSearch {
  data: {name:'morr', age: 19, email:'mor@mo.com' };
  apiurl: "http://localhost:3082";

Should be (note the '=' instead of ':'):

@Injectable()
export class PeopleSearch {
  data = {name:'morr', age: 19, email:'mor@mo.com' };
  apiurl = "http://localhost:3082";

The Typescript syntax for defining a property in a class is:

[name]:[type] = [value]

In your case you have defined the name and the type but not the value. Effectively you defined the property data and set the type so only objects exactly matching the properties and values you defined can be set to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM