Home > Net >  Angular post request to NodeJS JSON error
Angular post request to NodeJS JSON error

Time:07-01

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:

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".

CodePudding user response:

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

  • Related