Pedro
Pedro

Reputation: 11

SyntaxError: Unexpected token = in JSON at position 11 at JSON.parse (<anonymous>)

I can't figure it out why this is happening when I send a request via Insomnia using the PUT method. I'am trying to put a new title in a object that is in the projects[] array but it's not working out. This is the JS code:

const express = require('express');

const server = express();

server.use(express.json());

const projects = [];

server.post('/projects', (req, res) => {
  const { id, title } = req.body;

  const project = {
    id, 
    title,
    tasks: []
  };

  projects.push(project);

  return res.json(project);
})

server.get('/projects', (req, res) => {
  return res.json(projects);
})

server.put('/projects/:id', (req, res) => {
  const { id } = req.params;
  const { title } = req.body;

  for (let i = 0; i < projects.length; i++) {
    if(projects[i].id == id){
      projects[i].title = title;
    }
  }

  return res.json(project);
})

server.delete('/projects/:id', (req, res) => {
  const { id } = req.params;

  const projectIndex = projects.findIndex(p => p.id == id);

  projects.splice(projectIndex, 1);

  return res.json(projects);
})

server.listen(3000);

This is the request I sent:

{
    "title" = "new title"
}

This are my dev dependencies:

"dependencies": {
    "express": "^4.17.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.4"
  }
}

Upvotes: 0

Views: 1037

Answers (2)

Victor
Victor

Reputation: 181

Your Projects array is empty that means the code inside the loop will never be executed.

const projects = [{ id: 2, title: "old title" }];
app.put("/projects/:id", (req, res) => {
    const { id } = req.params;
    const { title } = req.body;
    for (let i = 0; i < projects.length; i++) {
        if (projects[i].id == id) {
            projects[i].title = title;
        }
    }

    res.send(projects);
});

After changing the code you posted to this and sending a put request to /projects/2 with the body {"title": "new title"}

The response is

[
  {
    "id": 2,
    "title": "new title"
  }
]

Upvotes: 0

Shivanshu Gupta
Shivanshu Gupta

Reputation: 324

The request you are sending is not valid. You have used = in json. It should be colan (:): Please replace this to:

{
    "title" : "new title"
}

Hope it will work!

Upvotes: 1

Related Questions