我使用过XMLHttpRequest和Promise。我将在pormise回调函数(then())中设置其他标头,该标头未设置为请求并且面对“对象的状态必须打开”。但是我已经在设置请求之前打开了。请找到代码段供您参考。
DOMException: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.
<div class="html5_upload">
<input type="file" id="upload" class="uploadBtn" name="UploadFiles" />
<button class="uploadBtn" onclick="uploadFiles()">Upload File</button>
</div>
<script>
function uploadFiles() {
var xhr = new XMLHttpRequest();
var file = document.getElementById('upload').files[0];
var formData = new FormData();
formData.append('UploadFiles', file);
xhr.open('POST', 'https://localhost:44310/api/values/save', true);
new Promise(function (resolve, reject) {
resolve();
}).then(function () {
xhr.setRequestHeader('custom', 'new');
});
xhr.onerror = function (args) {
console.log('error occurs..!');
}
xhr.send(formData);
}
</script>
答案 0 :(得分:0)
我认为您的 @Bean
public RestTemplate restTemplate() {
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
RestTemplate restTemplate = new RestTemplate(requestFactory);
List<HttpMessageConverter<?>> converters = new ArrayList<>();
StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
stringConverter.setWriteAcceptCharset(false);
converters.add(stringConverter);
restTemplate.setMessageConverters(converters);
restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
return new RestTemplate(requestFactory);
}
应该在xhr.send(formData)
内部。您可以尝试下面的代码,看看它是否按预期工作。
.then()