因此,我在我的网站上有一个我写新闻帖子的部分。我的想法是用HTML编写这些帖子,这样它们就会很漂亮。然后,我复制这段HTML代码并将其输入到Textarea元素中。然后,我尝试将此输入保存到Node.js后端的数据库中。
我用一个typeof text
检查了文本区域输入的类型,它返回了'string‘。我原以为现在可以将它发送到后端并保存在数据库中,但我注意到Node.js后端上的req.body
是空的。所以出了点问题。
有没有人知道更好的方法呢?
组件中的文本Console.log()返回这个(并且typeof声明它是一个字符串)
<h1>This is a test</h1>
<h2 class="test">Does it work or not?</h2>
<img src="https://ep01.epimg.net/cultura/imagenes/2017/11/08/1up/1510164524_440393_1510165636_noticia_normal.jpg">
addNews.component.ts
export class AddNewsPostComponent implements OnInit {
constructor(private newsService: LatestNewsService) {}
ngOnInit() {}
saveHtmlNewsPost(text) {
console.log(text);
console.log(typeof text);
this.newsService.saveNewsPost(text)
.subscribe((data) => {
console.log(data)
})
}
}
addPost.component.html
<textarea #htmlCode name="htmlCode" id="htmlCode" rows="30">
</textarea>
<button (click)="saveHtmlNewsPost(htmlCode.value)" class="btn btn-secondary btn-lg btn-block">Add Markup to Database</button>
<div class="row justify-content-center">
<div class=" col-md-10 sandBox">
<h1>This is a test</h1>
<h2 class="test">Does it work or not?</h2>
<img src="https://ep01.epimg.net/cultura/imagenes/2017/11/08/1up/1510164524_440393_1510165636_noticia_normal.jpg">
</div>
</div>
news.service.ts
saveNewsPost(text) {
console.log(typeof text);
return this.http.post('http://localhost:3000/news/saveNewsPost', text)
.pipe(catchError(this.handleError))
}
Node.js后端(console.log(req.body) )上的新闻路由返回一个空对象
router.post('/saveNewsPost', function(req, res){
console.log(req.body);
var newPost = new NewsArticle({
htmlCode: req.body
});
newPost.save(function(err, newsArticle){
if (err) {
return res.status(500).json({
title: "An error occurred",
error: err
})
}
res.status(200).json({
message: "Succesfully saved the newsArticle",
obj: newsArticle
})
})
});
发布于 2018-07-21 02:58:01
详细说明请参阅。https://angular.io/guide/forms。
Html
组件
export class AddNewsPostComponent implements
OnInit
{
htmlCode: string;
constructor(private newsService: LatestNewsService) {}
ngOnInit() {}
saveHtmlNewsPost() {
console.log(this.htmlCode);
console.log(typeof this.htmlCode);
this.newsService.saveNewsPost(this.htmlCode)
.subscribe((data) => {
console.log(data)
})
}
}
https://stackoverflow.com/questions/51448532
复制相似问题