我在 Symfony 项目中使用水银时遇到问题,我在项目的根目录安装了水银,但是,当我测试向水银发送请求时出现错误
无法连接到“http://localhost:3000/.well-known/mercury”的服务器
虽然 URL http://localhost:3000/.well-known/mercury 在本地很容易访问。
配置.env.local
:
MERCURE_PUBLISH_URL=http://localhost:3000/.well-known/mercure
MERCURE_JWT_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXJjdXJlIjp7InB1Ymxpc2giOlsiKiJdfX0.obDjwCgqtPuIvwBlTxUEmibbBf0zypKCNzNKP7Op2UM
配置.env
:
###> symfony/mercure-bundle ###
# See https://symfony.com/doc/current/mercure.html#configuration
MERCURE_PUBLISH_URL=http://localhost:3000/.well-known/mercure
# The default token is signed with the secret key: !ChangeMe!
MERCURE_JWT_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXJjdXJlIjp7InB1Ymxpc2giOlsiKiJdfX0.obDjwCgqtPuIvwBlTxUEmibbBf0zypKCNzNKP7Op2UM
###< symfony/mercure-bundle ###
美居命令:
./mercure --jwt-key='!ChangeMe!' --addr='localhost:3000' --allow-anonymous --cors-allowed-origins='*'
我的控制器:
<?php
namespace App\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mercure\PublisherInterface;
use Symfony\Component\Mercure\Update;
use Symfony\Component\Routing\Annotation\Route;
/**
* Class InterestController
* @package App\Controller
*/
class InterestController extends AbstractController
{
/**
* @Route("/profil/{user_id}/interets", name="user_interests", requirements={"user_id":"\d+"})
* @ParamConverter("user", options={"mapping": {"user_id" : "id"}})
* @ParamConverter("profil", options={"mapping": {"user_id" : "user_id"}})
*/
public function index()
{
return $this->render('interest/index.html.twig', [
'controller_name' => 'InterestController',
]);
}
/**
* @Route("/ping", name="ping", methods={"POST"})
* @param PublisherInterface $publisher
* @return Response
*/
public function __invoke(PublisherInterface $publisher): Response
{
$update = new Update(
'http://monsite.com/ping',
json_encode(['status' => 'OutOfStock'])
);
// The Publisher service is an invokable object
$publisher($update);
return new Response('published!');
}
}
测试前端:
{% extends 'base.html.twig' %}
{% block body %}
<form id="interest-form" action="{{ path('ping') }}" method="POST">
<a href="javascript:{}" onclick="document.getElementById('interest-form').submit();" class="send-interest">
</a>
</form>
{% endblock %}
{% block javascripts %}
<script>
// URL is a built-in JavaScript class to manipulate URLs
const eventSource = new EventSource('http://localhost:3000/.well-known/mercure?topic=' + encodeURIComponent('http://monsite.com/ping'));
eventSource.onmessage = event => {
// Will be called every time an update is published by the server
console.log(JSON.parse(event.data));
}
</script>
{% endblock %}
错误信息: