Home > Web Front-end > JS Tutorial > body text

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

Barbara Streisand
Release: 2024-11-01 21:10:29
Original
707 people have browsed it

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>
Copy after login

The correct origin, without the trailing slash, is:

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

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!