node.js - 错误:在 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.",
});
}
});
解决方案
推荐阅读
- matlab - Matlab 类型转换转移到 python 3.7
- jquery - 当在 jquery 中未选中复选框时,我试图从输入字段中删除 required
- azure - 如何为所有环境设置通用阶段管道?
- asp.net - 如何在 ASP.NET Core Web API 2.1 中添加 WCF 服务引用
- r - 一元运算符的无效参数 - R Shiny
- ios - 在 Highcharts 中加载图表时显示加载指示器
- c++ - 我如何清除数组
- node.js - 使用 mongodb、mongoose 和 nodejs 设置限制和偏移后获取集合总数
- ffmpeg - 如何从捕获设备捕获带有音频的简单视频输入
- java - EditText getText 在按钮单击中不起作用