0
votes

i am using nodeJS express as my backend also Angular2 as my Frontend. recently i am trying to upload a file to server by using multer package (handling in backend) and ng2-file-upload in my project.

when i am running on ng serve, it works perfectly.

when i deploy the app, i can login to my site (guess nodejs server running properly). but, while i uploading a file, it says these error

Access to XMLHttpRequest at 'https://sites.com/filetransfer/blog-images' from origin 'https://www.sites.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

while i hovering to error in network console,

Cross-Origin Resource Sharing Sharing Error: PreflightMissingAllowOriginHeader

kindly anyone has this issues?

here is my multer to handle upload routes

const multer = require('multer');
const createError = require('http-errors');

const _storage = multer.diskStorage({
    destination: async function (req, file, cb){
        cb(null, './uploads/blog-images');
    },
    filename: async function(req, file, cb){
        cb(null, Date.now()+'.'+file.originalname);
    }
});

const upload = multer({storage: _storage}).single('file');

module.exports = {
    base: async (req, res, next) => {
        res.send('ok');
    },
    blogimg: async (req, res, next) => {
        try {
            upload(req, res, async function(error){
                if(error) {
                    return createError.InternalServerError(error);
                }
                console.log({ originalname: req.file.originalname, uploadname: req.file.filename });
                return res.send({originalname: req.file.originalname, uploadname: req.file.filename})
            })
        } catch (error) {
            next(error)
        }
    }
}

here is also my fileuploader.service.ts

import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { FileUploader } from 'ng2-file-upload';
import { BehaviorSubject } from 'rxjs';

export interface UploadedFileName{
  originalname: string;
  uploadname: string;
}

@Injectable({
  providedIn: 'root'
})
export class FiletransferService {

  APIuploadblogimg = environment.baseHref+environment.fileTransferEndpoint.blogimg;
  uploader: FileUploader = new FileUploader({url: this.APIuploadblogimg});
  attachment: UploadedFileName = {
    originalname: '',
    uploadname: ''
  };

  constructor(
    private http: HttpClient
  ) {
    this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {
      this.attachment = JSON.parse(response);
      console.log(this.attachment);
    }
  }

  uploadBlogimg(file: string){
    return this.http.post<any>(this.APIuploadblogimg, {filename: file}, {
      responseType: 'blob' as 'json',
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      })
    })
  }
}

also here is my app.js for handling cors (so far)

...

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "https://www.sites.com");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.use(cors({origin: 'https://www.sites.com'}));
...

i've been working on this error for 1 days + today and still doesn't find the best solution. thanks

Oh, i am running on shared server with centos OS (cpanel)KrisnaRusdiono
What you try to upload a file, what’s the HTTP status code of the response? You can use the Network pane in browser devtools to check. If Chrome doesn’t show it, use the Network pane in Firefox devtools to check. Is it a 4xx or 5xx error rather than a 200 OK success response?sideshowbarker
On the server side of the https://sites.com/filetransfer/blog-images site, when you try to upload a file, what errors do you find in the server logs?sideshowbarker
oh i never use firefox, after trying to do what you said i findout there's no status code appear (4xx / 5xx). only red blocked icon 🚫KrisnaRusdiono