I'm having trouble uploading an image using Multer to my NodeJS backend. I'm using Axios to POST FormData Object containing a image and some data to my NGINX proxy server which will eventually save it in my Digital Ocean Space. Everything works perfectly in my development environment but when I try to upload in the file in production I get this error:
SyntaxError: Unexpected token - in JSON at position 0
at JSON.parse (<anonymous>)
at createStrictSyntaxError ...
Since I'm only getting this error in production environment I feel like this has something to do with my nginx proxy setup (this is the only thing that differs from production to development).
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 Config:
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;
}
I've exhausted all option on this site and others. Thank you in advance!
This can be an issue as you are passing Content-Type as application/json and uploading a file whose content-type is not json. Remove this header and try it once