0

I'm using Angular2, TypeScript to send a file, along with JSON Data to a server.

Html code

 <input type="file" class="form-control" name="avatar"   id="uploadyour" name="uploadyour"   #uploadyour="ngModel"  [(ngModel)]="model.uploadyour"  
           (change)="fileChange($event)"  placeholder="Upload file" accept=".pdf,.doc,.docx" >

app.component.ts.

import { Http, Headers, Response, Request, RequestMethod, URLSearchParams, RequestOptions } from "@angular/http";
import * as FileSaver from "file-saver";
import {Observable} from 'rxjs/Rx';
import { Injectable } from '@angular/core';

fileChange(event) { 
    let fileList: FileList = event.target.files;
    if(fileList.length > 0) {

        let file: File = fileList[0];
        let formData:FormData = new FormData();
        console.log(file);
        formData.append('uploadFile', file, file.name);
        let headers = new Headers();
        headers.append('enctype', 'multipart/form-data');
        headers.append('Accept', 'application/json');
        console.log(headers);
        let options = new RequestOptions({ headers: headers });
        console.log(formData);
        this.http.post("http://localhost:1337/trackstatus/upload", formData, options)
            .map(res => res.json())
            .catch(error => Observable.throw(error))
            .subscribe(
                data => console.log('success'),
                error => console.log(error)

            )
        }

    }



controller.js

upload: function  (req, res) {
     req.file('avatar').upload(function (err, files) {
      if (err)
        return res.serverError(err);

      return res.json({

        message: files.length + ' file(s) uploaded successfully!',

        files: files

                });
            });



        },

I am getting below error.

XMLHttpRequest cannot load http://localhost:1337/trackstatus/upload. Request header field enctype is not allowed by Access-Control-Allow-Headers in preflight response.

phani
  • 121
  • 1
  • 15
  • Possible duplicate of [Origin is not allowed by Access-Control-Allow-Origin](http://stackoverflow.com/questions/10143093/origin-is-not-allowed-by-access-control-allow-origin) – Tatsuyuki Ishi Apr 13 '17 at 11:47
  • Where I want to add "Access-Control-Allow-Origin" in app.component.ts or controller.js . – phani Apr 13 '17 at 12:23

1 Answers1

0

You need to update the settings on your server to allow AJAX requests from the domain that your Angular code is running on. This could be localhost or some other domain if your Angular app is already published somewhere. The specifics of how to change the CORS settings depends on your server side stack, but this SO answer shows the general fix:

https://stackoverflow.com/a/10143166/571237

Community
  • 1
  • 1
Sam Storie
  • 4,444
  • 4
  • 48
  • 74