"There are compatibility issues between Mercure, Symfony and Vue"
P粉023650014
2023-08-26 12:58:16
<p>I have a problem configuring mercure using vue and symfony. I'm using mercure hub attached in symfony cli. In the .env file I changed the url for mercure to use http as this would cause certificate errors (provided by symfony). </p>
<p><strong>.env</strong></p>
<pre class="brush:php;toolbar:false;">MERCURE_URL=http://localhost:8000/.well-known/mercure
MERCURE_PUBLIC_URL=http://localhost:8000/.well-known/mercure
MERCURE_JWT_SECRET="!ChangeMe!"</pre>
<p>When I open the symfony application in the browser (e.g. http://localhost:8000) and add the following script in the console for testing: </p>
<pre class="brush:php;toolbar:false;">const eventSource = new EventSource('http://localhost:8000/.well-known/mercure?topic=' encodeURIComponent('http://example .com/books/1'));
eventSource.onmessage = event => {
// This function will be called every time the server publishes an update
console.log(JSON.parse(event.data));
}</pre>
<p>It works and I can post some changes in other tabs.
However, when I do the same in my vue application located at http://localhost:8080, the console shows the following error: </p>
<pre class="brush:php;toolbar:false;">Access to resource at 'http://localhost:8000/.well-known/mercure?topic=http://example.com/books/1 ' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.</pre>
<p>Also, I have two more questions:</p>
<ol>
<li>Why do I get a 401 error when I paste the jwt token into the env, but not when using the above jwt token? </li>
<li>Why can't I use symfony serve with https? I encountered "TransportException: fopen(): Unable to locate certificate CN" error. </li>
</ol></p>
This is due to CORS, as VueJS is running on a different domain than the one Mercure is installed on.
I'm using Mercure with Docker compose, but if you launch it from the CLI, try adding
--cors-allowed-origins='http://localhost:8000 http://localhost:8080'
Additional Question 1: I think you should use the same key in .env and mercure configuration
.env
:MERCURE_JWT_SECRET="Secret123"
--jwt-key='Secret123'