search

Home  >  Q&A  >  body text

node.js - I use FormData() to upload images. In the background nodejs, the bodyparaer json method fails to parse... The code is as follows

First of all, the purpose is so that people can directly copy the pictures on other web pages and upload them when using them


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

In order to get the type of image, right

Here comes the key part

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

Then I submit it via ajax

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

The backend is abbreviated as Express. The master must know it
Dead routine

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

Then an error was reported

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

There is a problem with parsing, what should I do? I have tried many methods on the Internet, such as changing the header without using json. I tried it, but I still enter the bodypaarser.json method, and then get a -- error! !
Please God! Has anyone encountered similar problems

黄舟黄舟2774 days ago896

reply all(1)I'll reply

  • 巴扎黑

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

    However, after I restarted the project today, it was successful. For whatever reason, my code has not been changed. Weird! ! ! ! ! ! ! ! ! !

    reply
    0
  • Cancelreply