Vue项目API传参异常及CORS跨域PUT请求故障排查
问题解决指南
一、修正indexing_id参数传递错误
目标API路径要求indexing/journalID/indexingId.json,但你的代码目前只将journalID放入路径,且错误地把indexing_id作为请求体传递,同时组件方法未正确接收点击时传入的indexing_id,需按以下步骤修正:
1. 修正Indexin.vue中的deleteIndexing方法
- 方法需接收点击时传入的
indexing_id参数; - 构造包含journalID和indexing_id的完整路径片段:
<template> <div class="col-md-3 col-lg-3 col-sm-3 m-3 card" v-for="data in indexingList" :key="data.indexing_id"> <div> <base-button type="primary" size="sm" @click="deleteIndexing(data.indexing_id)" class="ml-4" >Delete</base-button > </div> </div> </template> <script> export default { methods: { deleteIndexing(indexingId) { // 构造包含journalId和indexingId的路径 const actionPath = `indexing/${store.state.journalId}/${indexingId}`; // 调用api时无需传递请求体(因indexing_id是路径参数) this.api.putData(actionPath).then((res) => { console.log(res.data); }, (error) => { console.log(error); }); } } } </script>
2. 优化api.js中的putData方法
若该接口无需请求体数据,可给data参数设置默认值避免报错:
putData (action, data = {}) { const url = `${BASE_URL}${action}.json`; return instance.put(url, data); }
二、解决CORS政策阻止PUT请求的问题
错误提示Method PUT is not allowed by Access-Control-Allow-Methods,需按以下方式处理:
- 后端配置调整:联系服务器开发人员,在CORS配置中添加
PUT到Access-Control-Allow-Methods列表; - 检查请求方法合理性:你的按钮是删除操作,若后端对应接口实际使用
DELETE方法而非PUT,则需修改代码:- 在api.js中新增deleteData方法:
deleteData (action) { const url = `${BASE_URL}${action}.json`; return instance.delete(url); } - 在Vue组件中调用deleteData替代putData:
this.api.deleteData(actionPath).then(...)
- 在api.js中新增deleteData方法:
内容的提问来源于stack exchange,提问作者saravana
相关产品推荐
相关产品推荐

