"NetworkError when attempting to fetch resource." 仅适用于 Firefox

"NetworkError when attempting to fetch resource." only on Firefox

我正在使用 fetch API 从我的前端发出 POST 请求。但是当我在 Firefox 中尝试时,它不起作用。在 Chrome 中工作正常。

这是我正在尝试做的事情。

const handleSubmit = async event => {
        try {
            await fetch(`https://api.example.net/api/route?slug=example`, {
                method: 'post',
                headers: {
                    'Content-Type': 'application/json',
                    'x-api-key': /* API KEY*/
                },
                body: JSON.stringify({
                    name,
                    email
                })
            })
                .then(response => console.log(response))
                .catch(err => console.log(err));
        } catch (error) {
            console.log(error);
        }
  };

所以,伙计们,这是解决方案。

问题是刷新表单的时间,在发送之前刷新。为了解决这个问题,设置响应时刷新表单,就完成了!

const handleSubmit = async event => {
        event.preventDefault();
        try {
            await fetch(`https://api.example.net/api/route?slug=example`, {
                method: 'post',
                headers: {
                    'Content-Type': 'application/json',
                    'x-api-key': /* API KEY*/
                },
                body: JSON.stringify({
                    name,
                    email
                })
            })
                .then(response => location.reload())
                .catch(err => console.log(err));
        } catch (error) {
            console.log(error);
        }
  };

我的情况是 CORS 问题 - 浏览器阻止了 POST 请求,因为服务器未设置 Access-Control-Allow-Headers 响应 header。在服务器上将其设置为“*”即可完成工作。

对我来说,这是添加 event.preventDefault()

的问题

如果您要发布到快速服务器,请确保请求和响应对象正在该服务器上的 POST 路由中使用。即使你只是 return res.send()。 None 其他解决方案对我有用。