GET方法工作正常,但是当我在我的角度项目中调用POST方法时,似乎没有调用nodeJs上的POST函数。我在做什么错了?
Angular服务:
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);
});
});
答案 0 :(得分:0)
也许您的帖子请求中需要一个“ 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' })
});
}