【问题标题】:How to POST method from Angular -> NodeJs/ExpressJs -> MySQL如何从 Angular -> NodeJs/ExpressJs -> MySQL POST 方法
【发布时间】:2019-05-23 04:22:04
【问题描述】:

GET 方法工作正常,但是当我在我的 Angular 项目上调用 POST 方法时,似乎 nodeJs 上的 POST 函数没有被调用。我做错了什么?

角度服务:

getAllProducts():  Observable<Product[]> {
return this.http.get<Product[]>('http://localhost:3000/api/content');
}

insertProduct(product: Product): Observable<Product> {
return this.http.post<Product>('http://localhost:3000/api/content', product);
}

server.js:

app.get('/api/content', function (req, res, next) {
    // query to the database and get the records
    mc.query('select * from testContent', function (err, recordset) {

        if (err) console.log(err)

        // send records as a response
        res.send(recordset); 
    });
});


app.post("/api/content",function(req , res, next){

    console.log('I will not get printed');

    mc.query('INSERT INTO testContent (productName,productCode) VALUES (\''+req.body.productName + '\',\'' + req.body.productCode + '\')',function (err, recordset) {

        if (err) console.log(err)

        // send records as a response
        res.send(recordset);

    });

});

【问题讨论】:

标签: mysql node.js angular express


【解决方案1】:

也许您的帖子请求中需要一个“Content-Type”标头,例如:

import { HttpClient, HttpHeaders } from '@angular/common/http';

insertProduct(product: Product): Observable<Product> {
  return this.http.post<Product>('http://localhost:3000/api/content', product, {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' })
  });
}

【讨论】:

    猜你喜欢
    • 2020-07-04
    • 2022-07-20
    • 2015-07-08
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多