首页 > 解决方案 > 错误:在 reactjs+NodejsBackend 中使用 fetch 或 axios 进行 POST、PUT、DELETE 请求的网络错误(缺少允许源头)

问题描述

大家好,我正在使用与 nodejs 后端服务器通信的 Reactjs 前端应用程序。所以现在当我使用服务器的 IP 地址在前端执行 API 时一切正常,但如果我使用域名切换到 https,则只允许 GET 请求,但所有其他请求(POST、DELETE、PUT)不工作和 axios 向我返回这样的错误 执行 api 请求时使用 Axios 错误的错误图像

现在如果我使用 fetch 我有这样的错误:

类型错误:获取失败

现在我在互联网上进行了深入的搜索,尤其是在 stackoverflow 中,但我找到的所有答案都无助于解决我的问题,因为尽管所有更改都导致相同的错误仍然存​​在。

这是我在后端 Nodejs 中测试过的代码:

1-我已经测试了这段代码:

   app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*')
    res.setHeader('Access-Control-Allow-Methods','OPTIONS, GET, POST, PUT, PATCH, DELETE')
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization')
    next()
})

2-我已经测试了这段代码:

const cors = require('cors');
app.use(cors())

这一切都没有效果!

这是我在 ReactJs 前端测试的代码:

await axios.put(`${baseUrl}/users/updateProfil/${id}`, data, {
          headers: {
            'Content-Type': 'application/json' ,
            'Authorization': `Bearer ${JSON.parse(token)}`
          }
        })
        .then(res => res.data).catch((e)=>{
          alert(e);
            console.log(e)
        });

并且无论我添加的修改如何,都有相同的错误:

 Error: Network Error
    at n.exports (createError.js:16)
    at XMLHttpRequest.g.onerror (xhr.js:84)

这是更新用户配置文件的代码:

router.put('/updateProfil/:id', async (req, res) => {
  var userId = req.params.id;
  var first_name = req.body.first_name;
  var last_name = req.body.last_name;
  var email = req.body.email;
  var country = req.body.country;
  var city = req.body.city;
  var phone = req.body.phone;
  var sender_sms_name = req.body.sender_sms_name;
  if (
    email &&
    phone &&
    city &&
    country &&  
    first_name &&
    last_name && 
    sender_sms_name
  )  {
    var user = await User.findOne({
      $or: [{ phone: phone }, { email: email }],
    }).select('-password').catch((error) => {
      res.status(404).json({
        success: false,
        val: 0,
        data: "error",
        message: "Something went wrong.",
      });
    }); 
    if (user != null) {
       await User.findByIdAndUpdate(userId, {
        first_name: first_name,
        email: email,
        last_name: last_name,
        phone: phone,
        city: city,
        country: country,
        sender_sms_name: sender_sms_name}, {new: true})
      .then( async(user) => {
        user= await User.populate(user, {path: 'sub_account'})
        return res.status(200).json({
          success: true,
          val: 1,
          data: user,
          message: "update done ",
        });
      });
    }else{
      return res.status(404).json({
        success: true,
        val: 1,
        data: "error while updating",
        message: "update success ! ",
      });
    }
   
  }else {
    return res.status(404).json({
      success: false,
      val: 0,
      data: "impossible to update!",
      message: "verify fields please.",
    });
  }
});

标签: node.jsreactjsaxios

解决方案


推荐阅读