Home > Article > Web Front-end > Why am I getting a CORS error when my server-side allows the origin with a trailing slash?
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 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>
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.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.
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!