“尝试获取资源时出现NetworkError。”仅在Firefox上

时间:2019-12-04 12:51:12

标签: javascript reactjs firefox fetch next.js

我正在使用POST API从前端进行一个fetch请求。但是当我在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);
        }
  };

3 个答案:

答案 0 :(得分:2)

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

的问题

答案 1 :(得分:1)

在我的情况下,这是一个CORS问题-浏览器阻止了POST请求,因为服务器未设置Access-Control-Allow-Headers响应标头。在服务器上将其设置为“ *”即可。

答案 2 :(得分:0)

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

问题是刷新表单的时间,发送之前正在刷新。要解决此问题,请设置为在响应时刷新表单,然后完成!

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);
        }
  };