D
D
dev_b2020-04-15 18:49:46
Yandex
dev_b, 2020-04-15 18:49:46

Yandex Cloud Functions Post Request how to defeat CORS?

Greetings. There is a function that sends a letter to the mail.

exports.handler = async (event, context) => {
  const { name, phone, email } = JSON.parse(event.body);

  ... отправка письма ...

  return {
    statusCode: 200
  };
};


Through Postman - everything is ok.
Through CORS Anywhere - everything is ok.

Via axios, fetch, etc. (everything from the front):

Access to fetch at 'https://functions.yandexcloud.net/***********' from origin 'https://xd71v.***********.io' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

POST https://functions.yandexcloud.net/*********** net::ERR_FAILED


Added the "Access-Control-Allow-Origin" header to the response body - no change.

Tell me which way to look, where to dig. Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
lmx, 2020-05-01
@lmx

Dev_by
Try to do it like this:
1. Remove headers if you installed Yandex functions in the answer, it does it for you.
2. Encode body to a string when sent via fetch/axios.
3. Set Content-Type: text/plain if it's different from text/plain .
An example of calling a function from a client:

fetch('https://functions.yandexcloud.net/<id функции>', {
    method: 'POST',
    body: JSON.stringify({ name: 'Max' })
})

An example of getting and processing body on the function side:
const formData = JSON.parse(Buffer.from(event.body, 'base64').toString());

D
dnagafonov, 2020-09-10
@dnagafonov

As indicated by the Yandex docs:
"No 'Access-Control-Allow-Origin' ..." when a request is generated by the browser,
the Yandex.Weather API is not intended to send requests from the user's browser. These actions are not secure, as they allow you to see your API key through browser tools.
If you need to make requests from a browser, use an intermediate server that will accept client requests, add an access key to them, and send requests to the Yandex.Weather API.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question