【问题标题】:How to update a record on mongo db through restapi?如何通过rest api更新mongodb中的记录?
【发布时间】: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


【解决方案1】:
  1. 我看不到您将数据发送到后端的位置。你设置了sweetscollection,但是你把它发送到后端哪里呢?要通过 fetch() 发送数据,您需要设置 fetch 请求的 body 属性 (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)

  2. 您还有一个 CORS 问题 - 这意味着服务器“不希望”与您的前端代码共享资源。您必须通过在 Express 服务器中设置 Access-Control-Allow-Origin 来解决这个问题,方法是添加:

添加Access-Control-Allow-Origin:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "YOUR-DOMAIN.TLD"); // update to match the domain you will make the request from
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.get('/', function(req, res, next) {
  // Handle the get for this route
});

app.post('/', function(req, res, next) {
 // Handle the post for this route
});

来源:https://enable-cors.org/server_expressjs.html

关于 CORS 的更多信息:https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

【讨论】:

  • 评论不用于扩展讨论;这个对话是moved to chat
  • 在服务器的 view/index.html 中你会看到两个按钮
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多