【发布时间】:2022-11-09 19:46:47
【问题描述】:
我有一个 express 节点 js 服务器,它在 3000 端口监听 localhost,并打印 JSON 内容。 如果我使用邮递员,它会正确打印 JSON。
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json())
var port = 3000;
app.post('/instance', function(req, res) {
const obj = JSON.parse(JSON.stringify(req.body))
console.log(obj);
//res.send(req.body);
});
// start the server
app.listen(port);
console.log('Server started! At http://localhost:' + port);
在 Angular html 中,我有一个 ngFor,它在单击按钮时发送一个列表项。
<ng-container *ngFor="let instance of instancesList">
<tr class="col-sm border border-primary" style="color:#111111">
<td>{{instance.id}}</td>
<td>{{instance.name}}</td>
<td>{{instance.zone}}</td>
<td>{{instance.ip}}</td>
<td> <button (click)="onClick(instance)" type="button" class="btn border-primary btn-lg">test</button></td>
</ng-container>
此时,当单击按钮时,我希望将带有项目数据的 JSON 发送到服务器,然后打印出来。它不会发生,服务器不打印 json 内容,但如果从邮递员发送,它会打印内容。
我已经挣扎了几天了,我很感激任何帮助。
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
};
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
@Injectable({providedIn:'root'})
export class AppComponent{
instancesList = instances;
baseUrl = "http://localhost:3000/instance"
constructor(private http: HttpClient) { }
onClick(instance: Instance) : Observable<Instance>{
const json = JSON.stringify(instance)
return this.http.post<Instance>(this.baseUrl, json, httpOptions)
// prints the json on the webpage just for testing
alert(JSON.stringify(instance));
}
}
我尝试搜索stackoverflow并尝试不同的方法,没有任何帮助。
【问题讨论】: