javascriptrestasynchronousfetchbackend

How to send a status code on RESTful controller api without an error?


VM1411:1 Uncaught (in promise) SyntaxError: Unexpected token 'O', "OK" is not valid JSON

When I fetch JSON(stringified object) data to the server and try to send a statusCode number 200 for indicating its status as OK in order to response, the client webpage keeps receiving that error for unknown reason. The server "can" take the JSON from the client-side, but only retrieving does not working right now. How to send the status code without getting an error?

client/js/product/index.js

var lotion = {
    name: "Vaseline",
    price: 20,
    skinProtection: true,
    protectionLevel: 10
};

class Order {
    constructor(method, target) {
        this.method = method;
        this.target = target;
        this.serve();
    }
    options(method, target) {
        return {
            method: method,
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(target)
        }
    }
    readAPI(path) {
        return fetch(`http://localhost:3500/controllers/product/${path}`, this.options(this.method, this.target))
    }
    async serve() {
       let receive = await (await this.readAPI('order')).json();
       console.log(receive);
    }
}

let getOrder = new Order('post', lotion)

server/app/controllers/index.js

const express = require('express');
const controllers = express.Router();

controllers.post('/product/order', async (req, res) => {
    console.log(req.body);
    res.sendStatus(200); // This causes that the browser receives an error
})

module.exports = controllers; // all the name must be matched

server/app/app.js

require('dotenv').config();

const express = require('express');
const cors = require('cors');
const path = require('path');

const app = express();
app.use(cors());
app.use(express.json());

const controllers = require('./controllers/index.js');
app.use('/controllers', controllers)

module.exports = app;

server/index.js

const app = require('./app/app.js');

app.listen(process.env.PORT, () => {
    console.log(`port: ${process.env.PORT}`);
})

File structure diagram

.
├── client/
│   ├── js/
│   │   ├── index/
│   │   └── product/
│   │       └── index.js
│   └── pages/
│       ├── index.html
│       └── product.html
└── server/
    ├── app/
    │   ├── controllers/
    │   │   └── index.js
    │   └── app.js
    ├── .env
    ├── node_modules
    ├── index.js
    ├── package-lock.json
    └── package.json

Attempts

  1. Added `"Accept": "application/json" to as a headers' property.
  2. Added .json({message: "OK"}) on res.sendStatus(200).

Solution

  • You said you are getting the error on the client webpage, right? It would be interesting if you could share how you are consuming this post endpoint in your client application, but I think the problem is that you are trying to transform the response from the endpoint into a JSON, and the sendStatus method only sends an "OK" string, which cannot be converted to JSON. You can try using:

    .status(200).send({ status: "success" }), for example!

    Or just don't use .json() in your client. Hope this helps!