我使用 axios 将 formdata
发送给我的 express 后端,当我不包括 config> config 对象作为第三个参数。但是,当包含 config
对象时,出现cors错误: coors screenshot错误
问题不应与前端代码有关,因为当我将同一请求( config
包括)发送给 formData 来实现的,但是我还没有费力地在这一部分上工作,因为我仍然对实际请求遇到问题。
请注意,如果我排除 config
对象,我可以在后端成功接收请求,例如:
await axios.post(`${import.meta.env.VITE_APP_API}/upload`, formData);
这是我的请求的样子,以及当前通过外部端点工作的内容,如前所述。但是,当发送到我自己的帖子端点时,同一请求也会导致CORS错误:
const config = {
signal: controller.signal,
onUploadProgress: (progressEvent) => {
progress.value = Math.round((progressEvent.loaded / progressEvent.total) * 100);
}
};
await axios.post(`${import.meta.env.VITE_APP_API}/upload`, formData, config);
这是我的帖子端点当前的样子:
router.post('/', (request, response) => {
response.set('Access-Control-Allow-Origin', '*');
console.log(request);
});
我应该如何修改我的帖子端点,以便它可以接收 config config
对象吗?我认为 axios 将这些信息作为标头传输,但似乎我的端点没有能力处理该请求。
I use Axios to send FormData
to my Express back-end, which works fine when I do not include the config
object as a third argument. However, when the config
object is included, a CORS error appears: screenshot of CORS error
The problem should not be with the front-end code, as there is no issue when I send the same request (config
included) to https://httpbin.org/post. I even receive the progress of the file upload from there - which is ultimately what I am after in my own back-end code. I know that this is achieved by parsing the FormData
, but I have not bothered working on that part yet, as I still have issues with the actual request coming through.
Note that I am able to successfully receive the request on the back-end if I exclude the config
object, like so:
await axios.post(`${import.meta.env.VITE_APP_API}/upload`, formData);
This is what my request should look like, and what is currently working through the external endpoint, as mentioned before. However, the same request also results in a CORS error when sent to my own POST endpoint:
const config = {
signal: controller.signal,
onUploadProgress: (progressEvent) => {
progress.value = Math.round((progressEvent.loaded / progressEvent.total) * 100);
}
};
await axios.post(`${import.meta.env.VITE_APP_API}/upload`, formData, config);
This is what my POST endpoint currently looks like:
router.post('/', (request, response) => {
response.set('Access-Control-Allow-Origin', '*');
console.log(request);
});
How should I modify my POST endpoint, so that it can receive the config
object as well? I assume that Axios transmits that information as headers, but it would seem that my endpoint is not equipped to handle the request anyway.
发布评论
评论(1)
我需要允许后端上的标头。
I needed to allow headers on the back-end.