P
P
Pavel Saenko2022-04-14 10:32:28
API
Pavel Saenko, 2022-04-14 10:32:28

Error sending request to api (express) server. 'Access-Control-Allow-Origin' How to fix?

When sending a request to the subdomain https://api.domain/ I get an error:

Access to XMLHttpRequest at 'https://api.domain/create' from origin 'https://domain' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.


PUT https://api.domain/create net::ERR_FAILED 403

At the same time, get requests are processed and return the necessary data from the database.


I have not worked with cors yet, please help me. Based on instructions on the Internet, I came to this decision. But as it turned out, nothing worked.

index.js

import express from "express";

import Router from "./routes/routes.js";

const app = express();

app.use(express.json());

app.use(Router);

app.listen(50002, () => console.log('Server is start at: ' + new Date().toLocaleTimeString()));


routes.js

import express from "express";

import cors from "cors";

import {
    get,
    getID,
    create,
    update,
    dell
} from "../controllers/product.js";

const router = express.Router();

var corsOptions = {
    credentials: true,
    preflightContinue: true,
    origin: 'https://domain',
    exposedHeaders: ['Content-Type'],
}

router.use(cors(corsOptions));

router.get('/getallusers', get)

router.get('/getid/:id', getID);

router.put('/create', create);

router.put('/update/:id', update);

router.delete('/dell/:id', dell);

export default router;


And directly the request to the api server

await axios.put(
                'https://api.edu.dniprorada.gov.ua/create',
                {
                  name: this.name,
                  mail: this.mail,
                  phone: this.phone,
                  social: this.social,
                  course: this.course,
                  sity: this.sity,
                },
                {withCredentials: true}
            )


6257cdfe80094886403429.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
TheAndrey7, 2022-04-15
@TheAndrey7

You cover up the domain badly. But the Cookies line must be covered without fail so that the session is not hijacked :)
To give the go-ahead to a cross-domain request, you need to respond with the Access-Control-Allow-Origin header in response, substituting the value of the Origin header received from the client with a preliminary domain check for the allowed list .

var corsOptions = {
    credentials: true,
    preflightContinue: true,
    origin: 'https://domain',
    exposedHeaders: ['Content-Type'],
}

What is actually indicated here in origin is unknown to me and I am not familiar with express. But you definitely need to substitute the Origin value from the Request Headers section here (see browser screenshot).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question