【问题标题】:upload image to Node.js Unexpected token将图像上传到 Node.js 意外的令牌
【发布时间】:2016-06-07 16:43:45
【问题描述】:

我想从android上传图片到node.js,关注this one,我现在可以从网上查看图片,但总是上传图片

SyntaxError: Unexpected token �

如果我选择 1.5mb 文件,它会显示

错误:请求实体太大

我找到了 this ,看来我必须将文件转换为 JSON

但我虽然已经使用这三个来加载大文件并将其转换为 JSON

app.use(bodyParser.json());
app.use(bodyParser.json({limit: '5mb'}));
app.use(bodyParser.urlencoded({ extended: true }))

卡在这里好几天了,请帮忙

代码

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var http = require('http');
app.use(bodyParser.json());
app.use(bodyParser.json({limit: '5mb'}));
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies.
songs = require('./routes/route');
var jsonParser = bodyParser.json();
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
app.get('/', function (req, res) {
  res.send('Hello World!');
});

app.get('/songs',songs.findAll);
app.get('/findById/:id',songs.findById);
app.post('/songs',songs.addSong);
app.put('/songs/:id',songs.updateSong);
app.delete('/songs/:id',songs.deleteSong);
app.post('/upload',songs.updateSong);
app.get('/upload/:file',songs.viewByFile);

路线代码

exports.upload = function(req, res) {
console.log(req.files.image.originalFilename);
console.log(req.files.image.path);
fs.readFile(req.files.image.path, function (err, data){
var dirname = "/Node/file-upload";
var newPath = dirname + "/uploads/" +   req.files.image.originalFilename;
fs.writeFile(newPath, data, function (err) {
  if(err){
    res.json({'response':"Error"});
  }else {
    res.json({'response':"Saved"});
  }
 });
});
};

错误

SyntaxError: Unexpected token �
at parse (c:\Users\awei\node_modules\body-parser\lib\types\json.js:83:15)
at c:\Users\awei\node_modules\body-parser\lib\read.js:116:18
at invokeCallback (c:\Users\awei\node_modules\raw-body\index.js:262:16)
at done (c:\Users\awei\node_modules\raw-body\index.js:251:7)
at IncomingMessage.onEnd (c:\Users\awei\node_modules\raw-body\index.js:308:7)
at emitNone (events.js:80:13)
at IncomingMessage.emit (events.js:179:7)
at endReadableNT (_stream_readable.js:906:12)
at nextTickCallbackWith2Args (node.js:475:9)
at process._tickCallback (node.js:389:17)

【问题讨论】:

    标签: android node.js


    【解决方案1】:

    如果您使用的是 postman 之类的扩展程序,请确保 Content-Type 在请求标头中是 multipart/form-data 而不是 application/json。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-19
      • 1970-01-01
      • 2012-09-21
      • 2019-08-07
      • 2018-11-10
      相关资源
      最近更新 更多