【发布时间】:2018-10-17 06:49:05
【问题描述】:
我正在尝试更新我的数据库中的数据。我在前端使用 jQuery/AJAX,在后端使用 REST/MyBatis/MySQL。不幸的是 REST 控制器返回 404 状态码。请看我的 REST 控制器代码:
@RestController
@RequestMapping("/documents")
public class DocumentResources {
private DocumentsMapper mapper;
public DocumentResources(DocumentsMapper mapper) {
this.mapper = mapper;
}
@PostMapping("/updateDocument")
public List<Documents> updateDocument (@RequestBody Documents document) {
mapper.updateDocument(document);
return mapper.getAllDocuments();
}
}
这是我的 DocumentsMapper 类代码:
@Mapper
public interface DocumentsMapper {
@Select("select * from documents")
List<Documents> getAllDocuments();
@Update("UPDATE documents SET title = #{title}, author = #{author}, src = #{src} WHERE id =#{id}")
void updateDocument(Documents document);
}
这是我的 AJAX 方法:
$( "#target" ).submit(function( event ) {
event.preventDefault();
var formData = {
id : $("#target #id").val(),
title : $("#target #title").val(),
author : $("#target #author").val(),
src: $("#target #src").val(),
createTime : $("#target #createTime").val(),
editTime : $("#target #editTime").val()
}
$.ajax({
url: 'http://localhost:8088/documents/updateDocument',
type : "POST",
contentType : "application/json",
data : JSON.stringify(formData),
dataType : 'json',
success : function(result) {
},
error: function() {
window.location = "/error";
console.log('error', arguments);
},
complete: function() {
console.log('complete', arguments);
}
}).done(function() {
window.location = "/documents";
console.log('done', arguments);
});
});
更新
我刚刚尝试关闭 Spring Security 并且 POST 方法变得可访问。以下是授权功能:
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**", "/signup", "/about").permitAll()
.antMatchers("/administrator/**").hasRole("ADMIN")
.antMatchers("/users/**").hasRole("ADMIN")
.antMatchers("/documents/**").hasRole("ADMIN")
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.logout().logoutSuccessUrl("/login?logout")
.and()
.exceptionHandling().accessDeniedPage("/403")
// .and()
// .csrf()
;
}
更新
我尝试打开 SpringSecurity 但禁用 CSRF .csrf().disable()。之后 POST 方法起作用。我认为禁用 CSRF 不是一个好主意。这可能会导致 XSS 攻击。所以我应该配置 CSRF-token 生成及其交换。
【问题讨论】:
-
你试过通过邮递员打你的rest api吗?那么输出是什么?
-
@Rinat 你能检查一下日志,是否显示“没有找到此 url 的映射”,还请在设置上下文路径后检查并尝试使用新的 url,这个链接很有帮助:@ 987654321@
-
@tryingtolearn 输出为:{"timestamp":"2018-10-17T07:08:26.074+0000","status":404,"error":"Not Found","message" :"没有可用的消息","path":"/documents/updateDocuments"}
-
这意味着您的应用程序中设置了一个上下文路径,需要在每个请求中附加。你用的是springboot吗?如果是,请检查 application.properties 中的上下文路径属性
-
@tryingtolearn only server.port and spring.datasource.url, spring.datasource.password, spring.datasource.username in my application.properties 文件。 GET REST 端点有效,但 POST 无效 (((