<script>
$(document).ready(function () {
$('#myForm').on('submit', function (event) {
event.preventDefault(); // 阻止默认提交行为
const formData = new FormData(this);
const dataObject = {};
formData.forEach((value, key) => {
dataObject[key] = value;
});
$.ajax({
url: 'http://127.0.0.1/api/user',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(dataObject),
success: function (response) {
console.log('Success:', response);
},
contentType: "application/x-www-form-urlencoded";
error: function (xhr, status, error) {
console.error('Error:', xhr.responseText);
}
});
});
});
</script>
加了跨域contentType: "application/x-www-form-urlencoded"; 可是运行网页还是出线错误:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sat Apr 27 16:16:04 CST 2024
There was an unexpected error (type=Unsupported Media Type, status=415).
nginx跨域的问题2
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
5条回答 默认 最新
关注 引自免费微信小程序:皆我百晓生
看起来你在尝试通过jQuery的
$.ajax()
方法向本地的Spring Boot应用发送一个JSON格式的POST请求,但是遇到了“Unsupported Media Type”(不支持的媒体类型)的错误,HTTP状态码为415。这通常是因为服务器端配置没有正确处理JSON数据。首先,确保你的Spring Boot应用已经配置了对CORS(跨源资源共享)的支持。在Spring Boot中,可以通过添加
@CrossOrigin
注解到控制器类或者特定方法上,或者全局配置来自定义CORS设置。这里是一个简单的例子,如何在Spring Boot中全局启用CORS:import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") // 这里设置允许所有路径的跨域访问 .allowedOrigins("*") // 允许任何来源发起跨域请求 .allowedMethods("*") // 允许所有方法(GET、POST等) .allowedHeaders("*"); // 允许所有头部 } }
然后,对于前端的AJAX请求,确认一下请求头中的
Content-Type
设置。根据你的代码片段,你已经设置了两次contentType
,这是不必要的。只需要保留一次,并且将其设置为正确的值。因为你的数据是以JSON格式发送的,所以应将Content-Type
设为application/json
。修改后的AJAX请求代码如下:<script> $(document).ready(function () { $('#myForm').on('submit', function (event) { event.preventDefault(); // 阻止默认提交行为 const formData = new FormData(this); const dataObject = {}; formData.forEach((value, key) => { dataObject[key] = value; }); $.ajax({ url: 'http://127.0.0.1/api/user', type: 'POST', contentType: 'application/json', data: JSON.stringify(dataObject), success: function (response) { console.log('Success:', response); }, error: function (xhr, status, error) { console.error('Error:', xhr.responseText); } }); }); }); </script>
现在,你应该可以在不报错的情况下发送JSON格式的POST请求了。记得重启Spring Boot应用,确保新的CORS配置生效。如果还有问题,检查一下Spring Boot日志输出,可能会有更详细的错误信息。
解决 无用评论 打赏 举报 编辑记录
悬赏问题
- ¥15 python点云生成mesh精度不够怎么办
- ¥15 QT C++ 鼠标键盘通信
- ¥15 改进Yolov8时添加的注意力模块在task.py里检测不到
- ¥50 高维数据处理方法求指导
- ¥100 数字取证课程 关于FAT文件系统的操作
- ¥15 如何使用js实现打印时每页设置统一的标题
- ¥15 安装TIA PortalV15.1报错
- ¥15 能把水桶搬到饮水机的机械设计
- ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
- ¥15 使用小程序wx.createWebAudioContext()开发节拍器