Skip to content

Commit b9189be

Browse files
authored
improvement: add newline remover for Header values (via #1468)
1 parent fe38245 commit b9189be

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

src/http.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,22 @@ export default async function http(url, request = {}) {
2424
// the search string, but much easier to manipulate the req.query object
2525
self.mergeInQueryOrForm(request)
2626

27+
// Newlines in header values cause weird error messages from `window.fetch`,
28+
// so let's massage them out.
29+
// Context: https://stackoverflow.com/a/50709178
30+
if (request.headers) {
31+
Object.keys(request.headers).forEach((headerName) => {
32+
const value = request.headers[headerName]
33+
34+
if (typeof value === 'string') {
35+
request.headers[headerName] = value.replace(/\n+/g, ' ')
36+
}
37+
})
38+
}
39+
40+
// Wait for the request interceptor, if it was provided
41+
// WARNING: don't put anything between this and the request firing unless
42+
// you have a good reason!
2743
if (request.requestInterceptor) {
2844
request = await request.requestInterceptor(request) || request
2945
}

test/http.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,29 @@ describe('http', () => {
331331
expect(response.status).toEqual(200)
332332
}).then(fetchMock.restore)
333333
})
334+
335+
test('should remove newlines from header values', () => {
336+
// Given
337+
fetchMock.get('*', (url, opts) => {
338+
return {
339+
body: opts.headers.WilliamCWilliamsHeader
340+
}
341+
})
342+
const req = {
343+
url: 'http://example.com',
344+
method: 'GET',
345+
headers: {
346+
WilliamCWilliamsHeader: 'so much depends\nupon\n\na red wheel\nbarrow'
347+
}
348+
}
349+
350+
return http('http://example.com', req).then((response) => {
351+
expect(response.url).toEqual('http://example.com')
352+
expect(response.data.toString()).toEqual(
353+
'so much depends upon a red wheel barrow'
354+
)
355+
}).then(fetchMock.restore)
356+
})
334357
})
335358

336359
describe('serializeRes', () => {

0 commit comments

Comments
 (0)