问题描述
发出简写后的ajax.post方法后,浏览器控制台报错,错误类型415.
const baseUrl = 'http://localhost:8181/api/mytest'
var post_data = {
    myTitle: "",
    myDescription: ""
}
ori.myTitle = $('#text_title').val()
ori.myDescription = $('#text_description').val()
$.post(baseUrl,JSON.stringify(ori),function(data){
    console.log(data);
})
出错415.原因分析:不是json格式。

image.png
第一种解决方法: 使用$.ajax()方法进行设定contentType。
$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: baseUrl,
    data: JSON.stringify(ori),
    cache: false,
    success: function(data) {
        console.log('将 JavaScript 值转换为 JSON 字符串后:');
        console.log(JSON.stringify(ori));
        console.log('返回成功后的数据:');
        console.log(data);
    },
    error: function() {
        console.log('失败');
    }
});
调试分析:请求头的Content-Type已修改。运行成功。

image.png
第二种解决方法:
参考: https://www.itranslater.com/qa/details/2111804812282037248
//对ajax进行全局设置。有效但影响了每一个$ .get和$ .post并导致一些破坏。
$.ajaxSetup({
    contentType: "application/json; charset=utf-8"
});
$.post(baseUrl,JSON.stringify(ori),function(data){
    console.log(data);
})