H
H
Herr_Shmulke2020-09-25 21:08:18
JavaScript
Herr_Shmulke, 2020-09-25 21:08:18

Why can't I send a POST request via Axios?

Server:

const corsConfig = {
  origin: `http://${host}`,
  optionsSuccessStatus: 200,
  credentials: true,
};

route.post('/login', cors(corsConfig), async (req, res) => {
...
}

I am using the cors module. Before that, I set the header myself, using
res.set('Access-Control-Allow-Origin', `http://${host}`);

Client side:
this.$axios.post(
          '/login',
          {
            mail: this.email,
            pass: this.password,
            remember: this.remember,
            reToken: token,
          },
          { withCredentials: true },
        );

As a result, I get an error in the console: Access to XMLHttpRequest at ' api.localhost/login ' from origin ' localhost ' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow- Origin' header is present on the requested resource.
I've been googling the problem all day and can't find a solution.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2020-09-26
@bingo347

The host variable on the server must be localhost for this to work, not the server host (or whatever you have).
Origin can be checked dynamically if you are polled by more than 1 host:
https://github.com/expressjs/cors#configuring-cors... You
can also pass RegExp or an array of strings/RegExp there:
https://github.com/ expressjs/cors#configuration-options

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question