NodeJS Multer Nginx上载错误:位置0处的意外令牌入JSON [英] NodeJS Multer NGINX Upload Error: Unexpected token - in JSON at position 0

查看:0
本文介绍了NodeJS Multer Nginx上载错误:位置0处的意外令牌入JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用Multer将图片上传到我的NodeJS后端。我正在使用Axios将包含图像和一些数据的FormData对象发布到我的Nginx代理服务器,该服务器最终会将其保存在我的数字海洋空间中。在我的开发环境中,一切都运行得很好,但当我尝试在生产环境中上传文件时,收到以下错误:

SyntaxError: Unexpected token - in JSON at position 0
    at JSON.parse (<anonymous>)
    at createStrictSyntaxError ...

由于我只在生产环境中收到此错误,我觉得这与我的nginx代理设置有关(这是不同于生产和开发的唯一不同之处)。

Axois:

export async function createPost(formData) {
  axios.post(`${config.SERVER}/create_post`, formData, {
    headers: { Authorization: `Bearer ${localStorage.getItem("token")}` }
  });
}

Express&;Multer:

const endpoint = new aws.Endpoint("sfo2.digitaloceanspaces.com/");

const s3 = new aws.S3({
  endpoint,
  accessKeyId: config.DO_SPACE_ACCESS_KEY,
  secretAccessKey: config.DO_SPACE_SECRET_KEY
});

var productionUpload = multer({
  storage: multerS3({
    s3,
    bucket: "bucket-name",
    acl: "public-read",
    contentType: multerS3.AUTO_CONTENT_TYPE,
    filename: (req, file, cb) => {
      cb(
        null,
        file.fieldname + "-" + Date.now() + `${path.extname(file.originalname)}`
      );
    }
  })
});

app.post(
  "/create_post",
  productionUpload.single("file"),
  verifyToken,
  create_post
);

nginx配置:

 location  API/ {
        proxy_pass http://localhost:3000/;
        proxy_http_version 1.1;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Content-Type 'application/json';

        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }


我已经用尽了这个站点和其他站点上的所有选项。提前感谢您!

推荐答案

这可能是一个问题,因为您正在将Content-Type作为应用程序/json传递,并上载内容类型不是json的文件。删除此标题并尝试一次

这篇关于NodeJS Multer Nginx上载错误:位置0处的意外令牌入JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆