Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion examples/runtime/xhr/src/xhr.js
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ export function postWithFormData(port) {
export function postWithJsonBody(port) {
console.log('XMLHttpRequest test 12: POST with JSON body');

return new Promise((resolve) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();

const jsonData = {
Expand All @@ -271,8 +271,29 @@ export function postWithJsonBody(port) {
xhr.onload = function() {
console.log(`JSON POST status: ${xhr.status}`);
console.log(`JSON response: ${xhr.response}`);

try {
const response = JSON.parse(xhr.response);
if (
xhr.status !== 200 ||
response.name !== jsonData.name ||
response.value !== jsonData.value
) {
reject(new Error('JSON echo response did not match the request'));
return;
}
} catch (error) {
reject(error);
return;
}

console.log('JSON response matched request: true');
resolve();
};

xhr.onerror = function() {
reject(new Error('JSON echo request failed'));
};

xhr.open('POST', `http://localhost:${port}/json-echo`);
xhr.setRequestHeader('Content-Type', 'application/json');
Expand Down
8 changes: 8 additions & 0 deletions tests/common/test_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,14 @@ pub async fn start_test_server() -> (u16, TestServerHandle) {
}))
}),
)
.route(
"/json-echo",
post(async move |Json(body): Json<serde_json::Value>| {
// For accepted JSON requests, extraction drains and validates the body before
// this handler builds the response.
Json(body)
}),
)
.route(
"/echo-referer",
post(async move |headers: HeaderMap, _body: Bytes| {
Expand Down
3 changes: 2 additions & 1 deletion tests/runtime/xhr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,8 @@ async fn xhr_post_with_json_body(
println!("{output}");

assert!(output.contains("XMLHttpRequest test 12: POST with JSON body"));
assert!(output.contains("JSON POST status:") || output.contains("ReadyState changed"));
assert!(output.contains("JSON POST status: 200"));
assert!(output.contains("JSON response matched request: true"));

Ok(())
}
Expand Down
Loading