在textarea中输入的HTML代码不会保存在数据库中

时间:2018-07-20 18:34:39

标签: javascript html node.js angular

因此,我在网站上有一个专栏文章撰写新闻。我的想法是用HTML编写这些帖子,以使其美观。然后,我复制此HTML代码并将其输入到Textarea元素内。然后,我尝试将此输入保存到Node.js后端的数据库中。

我用Call to a member function store() on null 检查了textarea输入的类型,并返回了'string'。我以为现在可以将其发送到后端并将其保存在数据库中,但是我注意到Node.js后端上的typeof text是空的。所以出了点问题。

有人知道更好的方法吗?

组件中的Console.log(文本)返回此字符(并返回类型为字符串的状态)

req.body

addNews.component.ts

<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">

addPost.component.html

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)
            })
    }
}

news.service.ts

<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>

Node.js后端上的新闻路由(console.log(req.body)返回一个空对象

saveNewsPost(text) {
        console.log(typeof text);
        return this.http.post('http://localhost:3000/news/saveNewsPost', text)
            .pipe(catchError(this.handleError))
    }

1 个答案:

答案 0 :(得分:0)

  • 使用ngModel双向数据绑定语法将数据属性绑定到每个表单控件。

请参见详细说明。 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)
        })
}

}