我是Angular的新手,并将其与node.js连接起来。 我正在尝试将电影JSON文件发送到我的服务器端以将其保存在我的数据库中。我设置了三个不同的文件。我的组件有一个按钮,它给出了命令(getMovie())来保存这个文件,我的服务文件试图向服务器端发送一个post请求,我的路由文件在服务器端处理POSt请求。
不幸的是我从未到达服务器端(我的日志中没有POST请求),我想知道你们是否能看到原因?\
组件文件:这里我将JSON数据发送到我的服务文件
for(field in SomeClass.declaredMemberProperties){
}
服务文件:此处我尝试与服务器建立连接
import {Component} from "@angular/core";
import {ListsService} from "./lists.service";
@Component({
selector: 'app-top100',
templateUrl: './top100.component.html',
styleUrls: ['./top100.component.css']
})
export class Top100Component {
link = "https://raw.githubusercontent.com/bantic/imdb-data-scraping/master/data/movies.json"
constructor(private listsService: ListsService){}
Get(yourUrl){
let Httpreq = new XMLHttpRequest(); // a new request
Httpreq.open("GET",yourUrl,false);
Httpreq.send(null);
return Httpreq.responseText;
}
getMovie() {
let json_obj = this.Get(this.link)
let ls = this.listsService;
setTimeout(function(){
ls.saveMovies(json_obj)
}, 3000)
}
}
服务器端的列表路由器文件
import {Injectable} from "@angular/core";
import 'rxjs/rx';
import {Headers, Http} from "@angular/http";
// We need @injectable if we want to use http
@Injectable()
export class ListsService {
constructor(private http: Http){}
saveMovies(obj){
const headers = new Headers({'Content-Type': 'application/json'});
this.http.post('http://localhost:3200/lists/savemovies', obj, {headers: headers});
}
}
app.js服务器端
var express = require('express');
var router = express.Router();
router.post('/savemovies', function(req, res, next) {
var body = JSON.parse(req.body);
console.log('hello');
console.log(typeof body);
console.log(body);
});
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;