Reputation: 3506
Same question on GitHub - https://github.com/axios/axios/issues/2743
I have Axios in my Next.js project and sometimes I get an error due to interceptor when return the Promise.reject
.
Error: Cannot set headers after they are sent to the client.
I encounter this problem when I make a request in getInitialProps
. This happens very rarely when I restart the PC and open the page again.
Axios instance:
const instance = axios.create({
baseURL: 'https://my-api.com',
withCredentials: true,
headers: {
'X-Requested-With': 'XMLHttpRequest',
},
})
instance.interceptors.response.use(undefined, error => {
if (error.response.status === 401) {
console.log("UNAUTHORIZED")
}
return Promise.reject(error) // <-- this cause the problem
})
Next.js Page example:
const Index = ({myData}) => {
return data.map(...)
}
Index.getInitialProps = async ({req}) => {
let myData
try {
const res = await API.get('/my-request', {
headers: req ? { cookie: req.headers.cookie } : undefined, //setting cookie
})
myData = res.data
} catch (e) {}
return {myData}
}
Upvotes: 2
Views: 2554
Reputation: 3506
This problem disappeared when I upgraded Axios 0.19.0 to 0.19.2 ¯_(ツ)_/¯
Upvotes: 1