关于javascript:SyntaxError:JSON中位置1 ||处的意外令牌e | 400错误的要求

SyntaxError: Unexpected token e in JSON at position 1 || 400 Bad Request

我正在尝试在Vue应用程序中提交表单数据。我有一个快速的后端API。我尝试发布的端点可以在邮递员上完美运行。我不断收到" SyntaxError:JSON在位置0处出现意外的令牌g"或" 400:错误的请求"

我尝试使用JSON.parse(this.description)。我试过了,没有解析this.description。

在axios配置文件中,我尝试在axios响应拦截器中将响应标头更改为" application / json"。我没有做也尝试过。

这是表格

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<v-dialog v-model="dialog" persistent max-width="600px">
      <template v-slot:activator="{ on }">
        <v-tooltip top>
          <v-btn small fab color="white" dark v-on="on" slot="activator">
            <v-icon color="primary">add</v-icon>
          </v-btn>
          <span>Add Task</span>
        </v-tooltip>
      </template>
      <v-card>
        <v-card-title>
          <span class="headline">Add Task</span>
        </v-card-title>
        <v-card-text>
          <v-form>
            <v-textarea v-model="description" label="Description"></v-textarea>
          </v-form>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="blue darken-1" flat @click="dialog = false">Close</v-btn>
          <v-btn color="blue darken-1" flat @click="addTask">Save</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

这是axios请求

1
2
3
4
5
6
7
8
9
10
11
12
methods: {
    ...mapActions(["fetchTasks"]),
    addTask() {
      console.log(this.description);
      axios
        .post("tasks", JSON.parse(this.description))
        .then(response => {
          dialog ="false";
        })
        .catch(err => console.log(err));
    }
  }

这是我的axios配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
"use strict";

import Vue from 'vue';
import axios from"axios";
import store from '../store';

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = '';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  baseURL:"http://localhost:3000/",
  timeout: 60 * 1000, // Timeout
  withCredentials: false, // Check cross-site Access-Control
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    let token = store.getters.getToken;

    if (token) {
      config.headers.common.Authorization = token;
    }

    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  function (response) {
    // Do something with response data
    return response;
  },
  function (error) {
    // Do something with response error
    return Promise.reject(error);
  }
);

Plugin.install = function (Vue, options) {
  Vue.axios = _axios;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      }
    },
    $axios: {
      get() {
        return _axios;
      }
    },
  });
};

Vue.use(Plugin)

export default Plugin;

这是端点

1
2
3
4
5
6
7
8
9
10
11
12
13
router.post('/tasks', auth, async (req, res) => {
  const task = new Task({
    ...req.body,
    owner: req.user._id
  });

  try {
    await task.save();
    res.status(201).send(task);
  } catch (err) {
    res.status(400).send();
  }
});

这是Google Chrome的"网络"标签下的标题数据。

Imgur


如果您的API需要JSON请求(根据您的评论),则需要将axios配置从以下位置更改:

1
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

至:

1
axios.defaults.headers.common['Content-Type'] = 'application/json';

出于良好的考虑,我还建议您使用这些,假设您希望接收JSON作为回报:

1
axios.defaults.headers.common['Accept'] = 'application/json';

并使用头显式声明所请求的内容:

1
axios.defaults.headers.common['X-Requested-With'] = 'XmlHttpRequest';

关于axios post调用,假设this.description是输入到输入字段或textarea中的文本,则需要构建JSON请求,如下所示:

1
2
3
.post("tasks", {
  'description': this.description
})

或设置数据对象,例如:

1
2
3
4
5
6
7
data () {
    return {
        formFields: {
            description: null
        }
    }
}

并将v模型更新为:

1
<v-textarea v-model="formFields.description" label="Description"></v-textarea>

,然后您可以使用:

1
.post("tasks", this.formFields.description)