axios 用过之后就不想在用了所以就用了fetch
在使用fetch请求由node构建 的服务的时候
get 请求能沟通过req,query请求过来参数但是post不行
所以需要引用body-parmr
或者使用formidable来进行post数据的解析
import formidable from 'formidable';
import timeFormater from 'time-formater';
import server from '../../server/article.js';
import publicJs from '../../prototyoe/public.js'
class articleController{
constructor(){
}
async newArticle(req,res,next){
const form = new formidable.IncomingForm();
form.parse(req,async (err,fields , files) => {
const {title, content,publishTime} = fields;
try{
if(!title){
throw new Error("文章标题不能为空");
}else if(!content){
throw new Error("文章内容不能为空")
}else if(!publishTime){
throw new Error("时间不能为空")
}
}catch(error){
res.send({
status:0,
type:"ERROR_ARTICLE",
message:error.message
})
}
try{
const article_id = await publicJs.articleId();
const Article = {
title:title,
content:content,
publishTime:publishTime,
// article_id : article_id
}
await server.articleDb(Article);
res.send({
status:1,
message:"保存文章成功"
})
}catch(error){
res.send({
status:0,
message:"保存文章失败"
})
}
})
}
};
if (window.fetch && method == 'fetch') {
let requestConfig = {
credentials: 'include',
method: type,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
}
if (type == 'POST') {
Object.defineProperty(requestConfig, 'body', {
value: JSON.stringify(data)
})
}
try {
const response = await fetch(url, requestConfig);
const responseJson = await response.json();
return responseJson
} catch (error) {
throw new Error(error)
}
}