app.component.ts
import { Component } from '@angular/core';
import { CharityService} from './app.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [CharityService]
})
export class AppComponent {
title = 'app';
[x: string]: any;
fname : string;
lname : string;
age : string;
address: string;
city : string;
constructor(private charityService:CharityService){
/* this.taskService.getTasks()
.subscribe(tasks => {
console.log(tasks);
}); */
}
addTask(event : any){
var tasks = {
fname : this.fname,
lname : this.lname,
age : this.age,
address : this.address,
city : this.city
}
console.log(event , tasks);
//console.log(this.userForm.value);
this.charityService.addTask(tasks).subscribe(data => {
console.log('Successful')
})
}
}
app.services.ts
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class CharityService {
constructor(private http: Http) {}
addTask(tasks){
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:4200/addTask', JSON.stringify(tasks), { headers: headers })
.map(res => res.json());
}
}
api.js
var express = require('express');
var router = express.Router();
var task = require('../models/model')
//var Model = require('../models/model.js');
router.post('/addTask', function(request, response) {
var task = new Model(request.body);
task.save(function(err, resource) {
if (err) {
response.send(err).status(501);
} else {
response.json(resource).status(201);
}
});
});
module.exports = router;
model.js
var mysql = require('mysql');
/* var Schema= mysql.Schema;
var CharitySchema = new Schema({
fname : String,
lname : String,
age : String,
address : String,
city : String
});
var Model = mysql.Model('task',CharitySchema);
module.exports = Model; */
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'charity_project'
});
connection.connect(function(err){
if(!err) {
console.log("Database is connected ... nn");
} else {
console.log("Error connecting database ... nn");
}
});
module.exports.addTask = function(tasks, callback) {
connection.query("INSERT INTO registration SET ?", tasks, callback);
}
app.component.html
<div class="container">
<h2 align="center"><u>Registration Form</u></h2>
<br>
<div class="container">
<form class="form-horizontal" #userForm="ngForm" (ngSubmit)="addTask($event)" >
<div class="form-group">
<label class="control-label col-sm-2" for="firstName">First Name:</label>
<div class="col-sm-10">
<input type="text" class="form-control" [(ngModel)]='fname' name="fname" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="lastName">Last Name:</label>
<div class="col-sm-10">
<input type="text" class="form-control" [(ngModel)]='lname' name="lname" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="age">Age:</label>
<div class="col-sm-10">
<input type="text" class="form-control" [(ngModel)]='age' name="age" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="address">Address:</label>
<div class="col-sm-10">
<input type="text" class="form-control" [(ngModel)]='address' name="address" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="city">City:</label>
<div class="col-sm-10">
<input type="text" class="form-control" [(ngModel)]='city' name="city" required>
</div>
</div>
<br>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</div>
server.js
var express = require('express');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var path = require('path');
var mainRouter = require('./routes/index');
var apiRouter = require('./routes/api');
var app = express();
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use((express.static(path.join(__dirname, 'src'))));
app.use('/', mainRouter);
app.use('/api', apiRouter);
port = process.env.PORT || 4200;
app.listen(port, function() {
console.log("listening to port " + port);
})
No deploying errors. But in here, when I input data it prints on Console. But it will not direct to the data base. It displays http://localhost:4200/addTask 404 (Not Found). Also it shows core.es5.js:1020 ERROR Response {_body: "↵↵↵Cannot POST /addTask↵↵↵", status: 404, ok: false, statusText: "Not Found", headers: Headers, …}
try for http://localhost:4200/api/addTask, as you are appending api in the route at app.use('/api', apiRouter);
I assume, You are using angular cli for angular development and running your angular project via ng serve
. If this is true, then you can't keep node js application port as 4200. Since, angular cli uses it by default, till we don't configure it to use some other port.
My suggestion will be that you choose, some other port no for your node js app.
The new url should be http://localhost:<new-port>/api/addTask
Hope you have done CORS configuration, if not please put the below code in your node js app index.js
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
next();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With