应用程序组件.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')
})
}
}
应用程序服务.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;
模型.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>
服务器.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);
})
没有部署错误。 但是在这里,当我输入数据时,它会打印在控制台上。但它不会指向数据库。它显示 http://localhost:4200/addTask 404(未找到)。它还显示 core.es5.js:1020 错误响应 {_body: "↵↵↵Cannot POST/addTask↵↵↵", status: 404, ok: false, statusText: "Not Found", headers: Headers, ...}
最佳答案
尝试 http://localhost:4200/api/addTask ,因为您在 app.use('/api', apiRouter); 的路由中附加 api
我假设,您正在使用 angular cli 进行 Angular 开发并通过 ng serve 运行您的 Angular 项目.如果这是真的,那么您不能将 node js 应用程序端口保留为 4200。因为,angular cli 默认使用它,直到我们不将其配置为使用其他端口。
我的建议是您为您的 Node js 应用程序选择一些其他端口号。
新的 url 应该是 http://localhost:<new-port>/api/addTask
希望你已经完成了 CORS 配置,如果没有请将下面的代码放在你的 node js 应用程序 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();
});
关于mysql - 发布 http ://localhost:4200/addTask 404 (Not Found) in Angular2 and node js but values are printing in console,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47048287/