【发布时间】:2020-01-27 00:29:37
【问题描述】:
每次我单击更新按钮时,都会出现一条错误消息,指出 CORS 策略已阻止从源“null”获取“http://localhost:3000/update”处的访问权限:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。
前端代码:
<form id="sweets">
ID: <input v-model="id" type="text" name="id"><br>
Sweet: <input v-model="sweetname" type="text" name="name"><br>
Price: <input v-model="price" type="text" name="price"><br>
<button v-on:click="update">Update</button>
</form>
客户端编码:
const app = new Vue({
el: "#app",
data: {
id: "",
name: "",
price: ""
},
methods: {
update() {
const sweetscollection = {
id: this.id,
name: this.name,
price: this.price
};
const options = {
method: "PUT",
headers: {
"Content-type": "application/json"
}
};
fetch("http://localhost:3000/update", options).then(response => {
console.log("success", response);
});
}
}
});
服务器端:
app.put("/update", (req, res, next) => {
req.collection.update(
{ _id: new ObjectID(req.params.id) },
{ $set: req.body },
{ safe: true, multi: false },
(e, result) => {
if (e) return next(e);
res.send(
result.result.n === 1 ? { msg: "success" } : { msg: "error" }
);
}
);
});
【问题讨论】:
-
您的客户端代码似乎正在访问
/update路由,而它应该是/sweets/sweets/:id路由。此外,您的客户端代码似乎没有将更新后的sweetscollection与您发送的 PUT 请求一起传递。 -
非常感谢。我尝试将其更改为 /update 路由,但它似乎没有替换数据。没用。
标签: mongodb rest express vue.js fetch