在我从npx create-react-app app-name
安装CRA然后运行yarn start
后,它将在http:/
中启动开发服务器/localhost:9000 默认情况下。
问题是,当我将 url 从浏览器地址栏复制到后端的 CORS 中间件时,该 url 显示 http://localhost:9000/
。这将引发错误Access-Control-Allow-Origin
not allowed,因为网址末尾有斜杠。
我想更改启动 CRA 开发服务器后在终端上显示的 url,并在 url 末尾添加斜杠 (http://localhost:9000/
),这怎么可能?恕我直言,网址末尾的斜杠使网址更漂亮呵呵。这就是为什么我想在 CORS 问题之外添加它。
谢谢!
最佳答案
对此没有绝对的规则。尾部斜杠是可选的。然而,一般理论是避免尾随斜杠。
Here你可以阅读更多相关内容。以下是所提供链接的片段。
You need to look at the HTTP request the browser makes to the server. The URL displayed in the "status bar of the browser", or even the URL in the address bar could be different - more user friendly. Google Chrome does not append the trailing slash in the status bar, although the slash is present in the request.
根据 Wikipedia 的帖子之一,尾部斜杠表示目录路径。
Adding a trailing "/" to a non-empty path. Directories (folders) are indicated with a trailing slash and should be included in URIs.
正如您已经了解的,URL http:localhost:9000
与 http://localhost:9000/
不同。它们是不同的 URL,这就是 CORS 不起作用的原因。 CORS URL 应该是域而不是特定的 URL。在您的情况下,您的域名是 http://localhost:9000
而不是 http://localhost:9000/
。因此,我确实会避免将 http://localhost:9000/
添加到 CORS 设置中。
在我个人看来,我会坚持浏览器的默认行为和大多数用户感知 URL 的常见概念,直到我有充分的理由更改它们。对我来说,没有额外斜杠的 URL 更漂亮:)
关于javascript - CRA 中是否有在 URL 末尾添加斜杠的设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61884383/