【发布时间】:2019-07-04 22:37:36
【问题描述】:
当我向 api symfony4 发送 post 请求时出现此错误。我使用 fosrestBundle 创建 api 并使用 nelmioCrosBundle 纠正错误 cros,但我也有此错误:
从源“http://localhost:4200”访问“http://localhost:8000/api/user/upload”处的 XMLHttpRequest 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。
代码配置nelmio:
nelmio_cors:
# defaults:
# origin_regex: true
# allow_origin: ['%env(CORS_ALLOW_ORIGIN)%']
# allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']
# allow_headers: ['Content-Type', 'Authorization']
# max_age: 3600
# paths:
# '^/': ~
paths:
'^/api':
allow_origin: ['*']
allow_headers: ['Authorization', 'Content-Type']
allow_methods: ['GET', 'POST', 'PUT', 'DELETE']
max_age: 3600
这是将数据角度发送到 symfony4 的函数:
uploadFiles(test) {
let headers = new Headers({ 'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.getItem('token') });
console.log(test);
return this._http.post(this.url + '/user/upload',JSON.stringify(test) ,{ headers: headers })
.pipe(map(res => res.json()));
}
我使用代理但也有错误,我还创建了侦听器来设置标题以响应但也有错误..如何解决此错误..
【问题讨论】: