我有一個骨幹客戶端應用程序和春天寧靜的服務器。客戶端應用程序位於localhost上,服務器端應用程序位於localhost:8080上。如果我的模型URL設置爲localhost,它將運行POST(明顯失敗)。如果我將URL設置爲正確的localhost:8080,它將運行OPTIONS。Backbone.js執行選項而不是POST
我已經實現了一個OPTIONS控制器,它可以響應請求。我可以在Chrome的開發工具和wfetch中正確地看到API。
但是POST從不運行。
這裏的客戶端代碼:
var cfd = function() {
var config = {
serverURL: 'http://localhost:8080'
};
function init(authString) {
var authHash = window.btoa(authString);
$.ajaxSetup({
headers: {
Authorization: 'Basic ' + authHash
}
});
}
var RegistrationModel = Backbone.Model.extend({
url: config.serverURL,
defaults: {
regFname: '',
regLname: '',
regHeardHow: 0
}
});
var AuthModel = Backbone.Model.extend({
url: config.serverURL,
defaults: {
action: ''
}
});
var UserModel = Backbone.Model.extend({
url: config.serverURL + '/user',
defaults: {
email: '',
fName: '',
lName: '',
heardHow: 0,
isDeleted: 0
}
});
return {
AuthModel: AuthModel,
RegistrationModel: RegistrationModel,
UserModel: UserModel,
config: config,
init: init
};
}();
而且......
var model;
cfd.init($('#email').val() + ':');
model = new cfd.UserModel({
email: '[email protected]',
fName: 'Test',
lName: 'Dude',
heardHow: 21,
isDeleted: 0
});
model.save();
這裏是我的API響應選項:
RESPONSE: **************\nHTTP/1.1 200 OK\r\n
Server: Apache-Coyote/1.1\r\n
Allow: POST,PUT,GET,DELETE,OPTIONS\r\n
Content-Length: 0\r\n
Date: Mon, 06 Jan 2014 16:30:31 GMT\r\n
\r\n
我已經響應代碼爲200,並試圖此204.
爲了完整起見,這裏是我的選擇控制器:
@Controller
public class OptionsController {
@Bean
public DispatcherServlet dispatcherServlet() {
DispatcherServlet servlet = new DispatcherServlet();
servlet.setDispatchOptionsRequest(true);
return servlet;
}
public static ResponseEntity<Void> allows(HttpMethod[] methods) {
HttpHeaders headers = new HttpHeaders();
Set<HttpMethod> allow = new HashSet<>();
for(HttpMethod method: methods){
allow.add(method);
}
headers.setAllow(allow);
return new ResponseEntity<>(headers, HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.OPTIONS)
ResponseEntity<Void> getProposalsOptions() {
HttpMethod[] methods = new HttpMethod[5];
methods[0] = HttpMethod.GET;
methods[1] = HttpMethod.PUT;
methods[2] = HttpMethod.POST;
methods[3] = HttpMethod.DELETE;
methods[4] = HttpMethod.OPTIONS;
return allows(methods);
}
}
和後控制器:
@Controller
public class PostController {
@Inject
private UserRepository users;
@RequestMapping(value = "/user", method = RequestMethod.POST)
public @ResponseBody void insertUser(@RequestBody final User user) {
users.save(user);
}
}
我在做什麼錯?
爲什麼Backbone在這種情況下做PUT?它不應該創造一個新的,發佈? – Lurk21
當isNew()爲true時,Backbone將不會運行PUT調用。這意味着如果在模型上設置了一個id,它將運行一個PUT,否則它會POST。 0,BTW,將返回false,因此將發出POST調用。 – oamsel
哦,當然這是有道理的 – Lurk21