首页 > 解决方案 > Javascript Axios 删除请求 ERR 失败

问题描述

我已经从我的 API Spring 中创建了一个按 ID 删除的方法,当我使用 Postman 执行请求时,一切正常,但是当我尝试使用我的代码执行此操作时,我遇到了错误。我正在使用 CORS 插件。GET 请求有效,但删除无效。我的代码如下和我的错误:方法删除:

DELETE(url) {
        try {
            console.log(axios.post(url, {
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                }
            }));
            return axios.delete(url)
        } catch (e) {
            return e;
        }
    }
  deleteDiscount(id) {
        return new Promise((resolve => {
            this.DELETE(`http://localhost:8080/discount/${id}`)
                .then(response => {
                    resolve(response.data)
                }).catch();
        }))
    }

所以,当我这样做时,我得到:

Access to XMLHttpRequest at 'http://localhost:8080/discount/d1' from origin 'http://localhost:63343' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
DELETE http://localhost:8080/discount/d1 net::ERR_FAILED
Uncaught (in promise) Error: Network Error
    at e.exports (isAxiosError.js:10)
    at XMLHttpRequest.l.onerror (isAxiosError.js:10)

并在控制台日志中:

_proto__: Promise
catch: ƒ catch()
constructor: ƒ Promise()
finally: ƒ finally()
then: ƒ then()
Symbol(Symbol.toStringTag): "Promise"
__proto__: Object
[[PromiseState]]: "rejected"
[[PromiseResult]]: Error: Network Error at e.exports (https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js:2:9719) at XMLHttpRequest.l.onerror (https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js:2:8491)
config: {url: "http://localhost:8080/discount/d1", method: "delete", headers: {…}, transformRequest: Array(1), transformResponse: Array(1), …}
isAxiosError: true
request: XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: ƒ, …}
response: undefined
toJSON: ƒ ()
message: "Network Error"
stack: "Error: Network Error\n    at e.exports (https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js:2:9719)\n    at XMLHttpRequest.l.onerror (https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js:2:8491)"
__proto__: Object

标签: javascriptaxios

解决方案


通过打开禁用安全性的 chrome 来修复。代码完美运行。编辑* 在 SPring api 上编写了 CORS 的配置,允许从任何地方进行,无需插件或禁用安全性即可完美运行。


推荐阅读