fetch 请求数据 以及 node 后端 post请求获取不到数据的记录

来源:互联网 发布:淘宝店铺分享链接生成 编辑:程序博客网 时间:2024/06/05 07:47

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:"保存文章失败"                        })                   }            })}};



但是post请求还是不成功最后才发现是因为在fetch中没有规定请求的数据是json格式的,导致了数据请求不成功


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




原创粉丝点击