So i am sending a POST request to a nodeJS app, my request in Angular looks like this:
newWord = '';
keyword = '';
onClick() {
const headers = new HttpHeaders()
.set('Authorization', 'my-auth-token')
.set('Content-Type', 'application/json');
this.http
.post('http://localhost:3000/search',{
keyword: this.keyword,
responseType: 'text',
headers: headers,
})
.subscribe((data) => {
console.log(data);
this.newWord = data as string;
})
}
My Node app post response is set like this:
app.post("/search", (req, res) => {
search(req.body.keyword).then((ids) => {
console.log(ids[0].text);
res.send(ids[0].text);
});
});
My problem is that when opening the console in the localhost i get this error
CodePudding user response:
Your HTTP POST request need to change (as @Drenai and @MikeOne stated in the comments):
this.http.post('http://localhost:3000/search',
{keyword: this.keyword},
{responseType: 'text',
headers: headers,
})
.subscribe((data) => {
console.log(data);
this.newWord = data as string;
})
CodePudding user response:
I can see you just sent a response as a text so on the client-side try parse response body giving issue.
so send a response in JSON format in the node itself I hope it helps.
app.post("/search", (req, res) => {
search(req.body.keyword).then((ids) => {
console.log(ids[0].text);
**res.send({response:ids[0].text});**
});
this.http
.post('http://localhost:3000/search',{
keyword: this.keyword,
headers: headers,
responseType: 'text',
})
.subscribe((data) => {
console.log(data['reponse']);
this.newWord = data['response'];
})