【发布时间】:2020-05-28 17:53:21
【问题描述】:
我在使用 Multer 将图像上传到我的 NodeJS 后端时遇到问题。我正在使用 Axios 将包含图像和一些数据的 FormData 对象发布到我的 NGINX 代理服务器,最终将其保存在我的数字海洋空间中。一切都在我的开发环境中完美运行,但是当我尝试在生产中上传文件时出现此错误:
SyntaxError: Unexpected token - in JSON at position 0
at JSON.parse (<anonymous>)
at createStrictSyntaxError ...
由于我只在生产环境中遇到此错误,我觉得这与我的 nginx 代理设置有关(这是生产与开发之间唯一不同的地方)。
轴突:
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;
}
我已经用尽了本网站和其他网站上的所有选项。提前谢谢!
【问题讨论】:
标签: node.js express nginx axios multer