“尝试获取资源时出现网络错误。” 仅在 Firefox 上

IT技术 javascript reactjs firefox fetch next.js
2021-05-04 02:48:46

我正在POST使用fetchAPI从我的前端发出请求但是当我在 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);
        }
  };
4个回答

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

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

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

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服务器未设置响应标头。在服务器上将其设置为“*”即可完成这项工作。

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