错误:发布到API时出现“请求失败,状态码为500”
直到这里,我添加了app.use(cors())时遇到了内部错误500,现在我遇到了跨源错误。
在我的代码中做了以下内容
const express=require('express')
const app=express();
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
app.use(cors());
app.post("/project",(req,res)=>cors(req,res,()=>{
const newProject={
title:req.body.title,
description:req.body.description,
status:req.body.status,
startdate:req.body.startdate,
enddate:req.body.enddate,
supervisor:req.body.supervisor,
createdAt:admin.firestore.Timestamp.fromDate(new Date())
}
admin.firestore().collection("Projects")
.add(newProject)
.then(doc=>{
return res.json({message:`Project ${doc.id} created successfully`})
})
.catch(err=>{
res.status(500).json({error:`Something went wrong, ${err}`})
})
}))
下面是客户端代码:
const newProject=JSON.stringify({
title:project.name,
description:"",
status:project.status,
startdate:project.startdate,
enddate:project.enddate,
supervisor:project.supervisor,
})
axios.post("https://us-central1-flair-d7b59.cloudfunctions.net/api/project",newProject)
.then(res=>{
this.setState({ open: false });
Swal.fire({
icon:"success",
toast:true,
title: res,
position: 'top-end',
showConfirmButton: false,
showClass: {
popup: ''
},
timer: 2500
})
})
.catch(err=>{
console.log(err)
this.setState({loading:false})
Swal.fire({
icon:"error",
toast:true,
title:"Something went wrong, Please try again",
position: 'top-end',
showConfirmButton: false,
showClass: {
popup: ''
},
timer: 2500
})
})
尝试了很多,但没有解决办法。谢谢
答案 0 :(得分:0)
我建议您使用cors
中间件来处理CORS握手,而不要手动进行。
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
到
app.use(cors());
在尝试使用请求主体之前,您也不会将其请求主体解析为JSON。这可以使用body-parser
中间件来实现。因为您使用JSON进行响应,所以我还假设您将数据作为JSON发送。
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const express = require('express');
const cors = require('cors');
const jsonBodyParser = require('body-parser').json();
admin.initializeApp();
const app = express();
app.use(cors()); // enable all origins
app.post("/project", (req,res) => {
jsonBodyParser(req, res, (err) => { // parse body as JSON
if (err) { // don't forget to handle errors when chaining to `next()` manually
res.status(500).json({error:'Failed to parse body as JSON'});
return;
}
const newProject= {
title: req.body.title,
description: req.body.description,
status: req.body.status,
startdate: req.body.startdate,
enddate: req.body.enddate,
supervisor: req.body.supervisor,
createdAt: admin.firestore.Timestamp.fromDate(new Date())
}
admin.firestore().collection("Projects")
.add(newProject)
.then(doc => {
return res.json({message:`Project ${doc.id} created successfully`})
})
.catch(err => {
res.status(500).json({error:`Something went wrong, ${err}`})
});
});
});
exports.app = functions.https.onRequest(app);