Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular post request to NodeJS JSON error

So i am sending a POST request to a nodeJS app, my request in Angular looks like this:

export class SearchComponent {
  constructor(private http: HttpClient) {}

  newWord = '';
  keyword = '';

  onClick() {
    const headers = new HttpHeaders()
      .set('Authorization', 'my-auth-token')
      .set('Content-Type', 'application/json');

    this.http
      .post('http://localhost:3000/search', JSON.stringify(this.keyword), {
        responseType: 'text',
        headers: headers,
      })
      .subscribe((data) => {
        this.newWord = data;
      });
  }
}

When i try to console.log the request i get an Unexpected token " in JSON at position 0 error even though i tried all the solutions i could find on stackoverflow this is how my NodeJS app is set and the error:

const bodyParser = require("body-parser");
const express = require("express");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.all("/*", function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
  res.header(
    "Access-Control-Allow-Headers",
    "Content-Type, Authorization, Content-Length, X-Requested-With"
  );
  next();
});

app.listen(3000, () => {
  console.log("Server is running on port 3000");
});

app.post("/search", (req, res) => {
  res.send(req.body);  
});

The error i get is this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SyntaxError: Unexpected token " in JSON at position 0
    at JSON.parse (<anonymous>)....

Note that the this.keyword gets its value from a input field if i dont use JSON.stringify no error is happening but the req variable is "undefined".

>Solution :

Assuming you are asking how to get back the data. I’m not sure if this will work, but you can give it a try:

Under comments, see that you mean this.keyword. Here is the change I would make

going by axis format, this may be incorrect

.post('http://localhost:3000/search', JSON.stringify(this.keyword), {
        responseType: 'text',
        headers: headers,
      })

instead, try:

.post('http://localhost:3000/search', {
        keyword: this.keyword, // changed this
        responseType: 'text',
        headers: headers,
      })

also in your server, you can change to this:

const app = express();
app.use(express.json())
app.use(express.text())
app.use(express.urlencoded({ extended: true }))

(body parser included in express now)

new to the mern stack (have never used Angular) so kind of iffy but hopefully that can help

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading