0

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:'[email protected]' };
  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??

1 Answer 1

1

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:'[email protected]' };
  apiurl: "http://localhost:3082";

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

@Injectable()
export class PeopleSearch {
  data = {name:'morr', age: 19, email:'[email protected]' };
  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.

Sign up to request clarification or add additional context in comments.

1 Comment

Great. Thanks. i was only looking at the various syntax and made mistake while defining data. Thanks for pointing that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.