首页  >  问答  >  正文

node.js - 我用FormData() 来上传图片,后台nodejs,bodyparaer json方法解析失败......代码如下

首先 目的是为了人们用的时候可以直接复制其他网页上的图片直接拷贝过来,上传


codeMirror.on('paste', this.paste.bind(this));
//是不是在paste方法中就会有codemirror 的方法,知道的应该懂
const file = clipboard(e.clipboardData.items);


//上面那个方法就是 
function clipboard(items) {
  let i = 0;
  let item;
  while (i < items.length) {
    item = items[i];
    if (item.type.indexOf('image') !== -1) {
      return item;
    }
    i++;
  }
  return false;
}

为了取出来image的类型对吧

关键的地方来了

const formData = new FormData();
formData.append('file', file.getAsFile(), 'image.png');

然后我再ajax提交

tools.ajax({
             url: ajaxProps.action,
             method: 'POST',
             data:formData,
            //  headers:{'Content-Type':'application/json'},
             async: true,
             dataType:ajaxProps.dataType,
             processData: false,
         }).....

后台就简写express大神肯定知道
死套路

app.use(bodyParser.json());
// app.use(bodyParser.multipart());
app.use(bodyParser.urlencoded({extended: true}));

然后就报错了

SyntaxError: Unexpected token -
    at parse (C:\Users\wb-yuhaiqing.a\Desktop\discount\web_corpoation\node_modules\.1.17.1@bo
dy-parser\lib\types\json.js:83:15)
    at C:\Users\wb-yuhaiqing.a\Desktop\discount\web_corpoation\node_modules\.1.17.1@body-pars
er\lib\read.js:116:18
    at invokeCallback (C:\Users\wb-yuhaiqing.a\Desktop\discount\web_corpoation\node_modules\.
2.2.0@raw-body\index.js:262:16)
    at done (C:\Users\wb-yuhaiqing.a\Desktop\discount\web_corpoation\node_modules\.2.2.0@raw-
body\index.js:251:7)
    at IncomingMessage.onEnd (C:\Users\wb-yuhaiqing.a\Desktop\discount\web_corpoation\node_mo
dules\.2.2.0@raw-body\index.js:307:7)
略

解析出了问题,怎么办,试了网上好多方法,比如 改header ,不用json ,我试了,还是会进入这个bodypaarser.json 方法里面去,然后 抱一个 -- 的错误!!
求大神!有没有人遇到过类似问题

黄舟黄舟2680 天前815

全部回复(1)我来回复

  • 巴扎黑

    巴扎黑2017-05-24 11:40:44

    然而我今日重启项目以后 ,成功了。 我母鸡啥原因,代码没改过, 奇葩!!!!!!!!!!

    回复
    0
  • 取消回复