Home  >  Article  >  Web Front-end  >  Why am I getting a CORS error when my server-side allows the origin with a trailing slash?

Why am I getting a CORS error when my server-side allows the origin with a trailing slash?

Barbara Streisand
Barbara StreisandOriginal
2024-11-01 21:10:29691browse

Why am I getting a CORS error when my server-side allows the origin with a trailing slash?

Why am I getting a CORS error even though I've allowed the origin https://example.com/?

Understanding CORS Origins

Cross-Origin Resource Sharing (CORS) is a mechanism that restricts cross-origin requests from third-party websites to protect sensitive data. An origin is represented by a combination of the protocol, domain, and port.

The Trailing Slash Issue

The key issue here is the presence of a trailing slash in the allowed origin.

Web origins do not contain trailing slashes. Therefore, the following origin is invalid:

<code class="text">https://googledocs-clone-sbayrak.netlify.app/</code>

The correct origin, without the trailing slash, is:

<code class="text">https://googledocs-clone-sbayrak.netlify.app</code>

Socket.IO CORS Configuration

In Socket.IO, you're using the Node.js cors package for CORS handling. This package requires an exact match between the request's origin and the origin value configured in the CORS settings. With a trailing slash in the origin, the comparison fails and no Access-Control-Allow-Origin header is set in the response.

Your Server-Side Code

Your server.js file has CORS middleware configured as follows:

<code class="javascript">const io = socketio(server, {
  cors: {
    origin: 'https://googledocs-clone-sbayrak.netlify.app/',
    methods: ['GET', 'POST'],
  },
});</code>

Remove the trailing slash from the origin value.

Frontend Request

In your frontend code, the socket connection is made to the following address:

<code class="javascript">const s = io('https://googledocs-clone-sbayrak.herokuapp.com/');</code>

Using the correct origin value without the trailing slash, the CORS error should no longer occur.

The above is the detailed content of Why am I getting a CORS error when my server-side allows the origin with a trailing slash?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn