v-on处理程序变量this中的VueJS错误。未定义

时间:2019-04-05 16:25:37

标签: javascript vue.js this-pointer

在VueJS中使用MongoDB / Express后端api,尝试通过单个字段url将新记录添加到Bookmarks模型中,但收到一个错误,我尝试传递的url字段是{{ 1}}。之前我已经将此模式用于api调用,所以没有问题,所以我不确定这次会发生什么。

从控制台:

undefined

在“网络”标签中:

Error in v-on handler (Promise/async): "Error: Request failed with             status code 500"

这是组件:

{"errors":{"message":"Cannot read property 'url' of undefined","error":{}}}

后端的api调用通过services文件夹来实现,因此在BookmarksService.js中:

<template>
  <div class="bookmarks">
    <h1>Add a Bookmark</h1>
    <div class="form">
      <div>
        <input type="text" placeholder="Enter a URL" v-model="url">
      </div>
      <div>
        <button class="app_post_btn" @click="addBookmark">Save</button>
      </div>
    </div>
  </div>
</template>

<script>
import BookmarksService from '@/services/BookmarksService'
export default {
  name: 'NewBookmark',

  data () {
    return {
      url: ''
    }
  },
  methods: {
    async addBookmark () {
      await BookmarksService.addBookmark({
        url: this.url
      })
      this.$router.push({ name: 'Bookmarks' })
    }
  }
}
</script>

<style type='text/css'>
.form input,
.form textarea {
  width: 500px;
  padding: 10px;
  border: 1px solid #e0dede;
  outline: none;
  font-size: 12px;
}
.form div {
  margin: 20px;
}

.app_post_btn {
  background: #4d7ef7;
  color: #fff;
  padding: 10px 80px;
  text-transform: uppercase;
  font-size: 12px;
  font-weight: bold;
  width: 520px;
  border: none;
  cursor: pointer;
}
</style>

Api.js:

import Api from '@/services/Api'

export default {
  fetchBookmarks () {
    return Api().get('bookmarks')
  },

  addBookmark (params) {
    return Api().post('bookmarks', params)
  }
...

针对下面的评论,以下是请求信息:

import axios from 'axios'
const token = localStorage.getItem('token')

export default () => {
  return axios.create({
    baseURL: 'http://localhost:8000/api',
    headers: {
      'Content-Type': 'application/json',
      token: token,

    }
  })
}

在服务器端:

这是发布路线:

Request URL: http://localhost:8000/api/bookmarks
Request Method: POST
Status Code: 500 Internal Server Error
Remote Address: [::1]:8000
Referrer Policy: no-referrer-when-downgrade
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 75
Content-Type: application/json; charset=utf-8
Date: Fri, 05 Apr 2019 16:47:01 GMT
ETag: W/"4b-DnvHolHvXjMbxmLeqrleWSWRA0Q"
X-Powered-By: Express
Provisional headers are shown
Accept: application/json, text/plain, */*
authorization: Token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InVzZXJvbmVAZ21haWwuY29tIiwiaWQiOiI1YzlmOTcxY2E3YzIyNTc1ZTFjYzkwMDUiLCJleHAiOjE1NTk2NjY3ODcsImlhdCI6MTU1NDQ4Mjc4N30.zlrqFfj2r7K_1iAVm7m2w_kUeqFH3ZvsDJkIK7UOUu8
Content-Type: application/json
Origin: http://localhost:8080
Referer: http://localhost:8080/
token: Token undefined
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36
{url: "http://axios.com"}
url: "http://axios.com"

快递应用中的app.js文件:

const mongoose = require('mongoose');
const passport = require('passport');
const router = require('express').Router();
const auth = require('../auth');
const Bookmarks = mongoose.model('Bookmarks');

//POST new user route (optional, everyone has access)
router.post('/', auth.required, (req, res, next) => {
  const userId = req.user.id;
  const bookmark = req.body.bookmark;

  if(!bookmark.url) {
    return res.status(422).json({
      errors: {
        url: 'is required',
      },
    });
  }

  bookmark.userId = userId;
  const finalBookmark = new Bookmarks(bookmark);

  return finalBookmark.save()
    .then(() => res.json({ bookmark: finalBookmark }));
});

...

2 个答案:

答案 0 :(得分:0)

请参见以下代码段。始终验证来自身体的任何财产。

router.post('/', auth.required, (req, res, next) => {
  const userId = req.user.id;
  const bookmark = req.body.bookmark; <---- bookmark is undefined

  if(!bookmark.url) { <---- undefined.url -> Error.
    return res.status(422).json({
      errors: {
        url: 'is required',
      },
    });
  }

  // ...
});

答案 1 :(得分:0)

来自您的前端的请求的主体不是您所期望的。
这里的主要问题是,在vue.js组件的addBookmark功能中,您传递的是具有唯一属性“ url”的对象,而在后端服务中,您期望的是包含属性“ url”的“ bookmark”对象。 您也可以在请求的正文中看到它:{url: "http://axios.com"} 将您的组件代码更改为

async addBookmark () {
  await BookmarksService.addBookmark({
    bookmark: {
               url: this.url
           }
  })
  this.$router.push({ name: 'Bookmarks' })
}

应该工作。您应该获得类似{ bookmark: {url: "http://axios.com"} }的内容。 无论如何,请验证来自请求正文的任何​​属性,如Phil所说的,这始终是您应遵循的良好做法。