我正在尝试使用Angular 4中的POST请求发送带有文件的表单数据。如果标头为var patternToSearch = {"test":"/^test/g"};
var source = patternToSearch.test.match(/\/(.*)\/(.*)/);
// source[1] contains patterns, source[2] contains flags
var pattern = new RegExp(source[1], source[2]);
// Logging our tests
console.log(pattern.test("testing"));
console.log(pattern.test("not-testing"));
,则表单数据不会发送到服务器。如果标头是'Content-Type': 'application/json'
,则客户端可以将表单数据发送到服务器。但在邮递员申请/ json将工作。我想在Angular 4中使用相同的内容。
Component.ts: `
'Content-Type': 'multipart/form-data'
HTML:
let formData: FormData = new FormData();
formData.append("courseId", this.course_id.toString());
formData.append("courseName", this.course_name.toString());
formData.append('pic', this.file);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers,withCredentials: true });
this.http.post('http://localhost:3000/createNew', formData, options)
.map(res => res.json())
.catch(error => Observable.throw(error))
.subscribe(
data => console.log('success'),
error => console.log(error)
)`
答案 0 :(得分:2)
要以角度或任何地方提交formdata
,其内容类型不应为Json
。
所以你可以这样做:
let formData: FormData = new FormData();
formData.append("courseId", this.course_id.toString());
formData.append("courseName", this.course_name.toString());
formData.append('pic', this.file);
let headers = new Headers({ 'Content-Type': 'multipart/form-data' });
let options = new RequestOptions({ headers: headers,withCredentials: true });
this.http.post('http://localhost:3000/createNew', formData, options)
.map(res => res.json())
.catch(error => Observable.throw(error))
.subscribe(
data => console.log('success'),
error => console.log(error)
)`
答案 1 :(得分:0)
'Content-Type': 'multipart/form-data'
标头告诉浏览器不应对请求的内容进行编码。例如,当表单需要二进制数据(如文件内容)时,您需要这样做。
邮递员很可能会忽略/删除application/json
邮件。