Created the server API and everything stopped working after adding this fragment:

app.use((req,res,next) => { res.header('Access-Control-Allow-Origin','*') res.header('Access-Control-Allow-Headers','Origin, X-Requested-With, Content-Type, Accept, Authorization') if(req.method === 'OPTIONS'){ res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE , GET') return res.status(200).json({}) } }) 

Here is the full code:

 const express = require('express') const cors = require('cors') const bodyParser = require("body-parser") const morgan = require('morgan') const app = express() const productRoutes = require('./routes/products') const ordersRoutes = require('./routes/orders') app.use(morgan('combined')) app.use(bodyParser.urlencoded({extended : false})) app.use(bodyParser.json()) app.use(cors()) //headers app.use((req,res,next) => { res.header('Access-Control-Allow-Origin','*') res.header('Access-Control-Allow-Headers','Origin, X-Requested-With, Content-Type, Accept, Authorization') if(req.method === 'OPTIONS'){ res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE , GET') return res.status(200).json({}) } }) //--headers app.use('/products',productRoutes) app.use('/orders',ordersRoutes) //Обработочка ошибочек app.use((req,res,next) => { const error = new Error('Not found') error.status = 404 next(error) }) app.use((error,req,res,next) => { res.status(error.status || 500) res.json({ error:{ message:error.message } }) }) //Обработочка ошибочек-- app.listen(process.env.PORT || 8081 ) 

Tell me, please, where I was wrong.

So fixed to work:

 app.use((req,res,next) => { res.header('Access-Control-Allow-Origin','*') res.header('Access-Control-Allow-Headers','Origin, X-Requested-With, Content-Type, Accept, Authorization') if(req.method === 'OPTIONS'){ res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE , GET') return res.status(200).json({}) } next() }) 

    1 answer 1

    It is very important to transfer the processing of the request further. You forgot to call next () .

     // Add headers app.use(function (req, res, next) { // Website you wish to allow to connect res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888'); // Request methods you wish to allow res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // Request headers you wish to allow res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); // Set to true if you need the website to include cookies in the requests sent // to the API (eg in case you use sessions) res.setHeader('Access-Control-Allow-Credentials', true); // Pass to next layer of middleware next(); }); 
    • Thank you! Earned) That is how I changed the code inserted into the answer. - Oleksandr Tatarinov