Problem Description:
I'm working on a React application that interacts with an external API using Axios. I'm encountering a "401 Unauthorized" error when making a POST request to the API's /api/conversation
endpoint. I've double-checked my authentication credentials and headers, but the issue persists.
Code Snippet:
const onSubmit = async (values: z.infer<typeof formSchema>) => {
try {
const userMessage: ChatCompletionRequestMessage = { role: "user", content: values.prompt };
const newMessages = [...messages, userMessage];
const response = await axios.post('/api/conversation', { messages: newMessages },{ withCredentials: true })
setMessages((current) => [...current, userMessage, response.data]);
form.reset();
} catch (error: any) {
console.log(error)
} finally {
router.refresh();
}
AxiosError {message: 'Request failed with status code 401', name:
'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request:
XMLHttpRequest, …}code: "ERR_BAD_REQUEST"config: {transitional: {…},
adapter: 'xhr', transformRequest: Array(1), transformResponse: Array(1),
timeout: 0, …}message: "Request failed with status code 401"name:
"AxiosError"request: XMLHttpRequest {onreadystatechange: null, readyState:
4, timeout: 0, withCredentials: false, upload:
XMLHttpRequestUpload, …}response: {data: 'Unauthorized', status: 401,
statusText: '', headers: AxiosHeaders, config: {…}, …}stack: "AxiosError:
Request failed with status code 401\n at settle (webpack-
internal:///(app-pages-
browser)/./node_modules/axios/lib/core/settle.js:24:12)\n at
XMLHttpRequest.onloadend (webpack-internal:///(app-pages-
browser)/./node_modules/axios/lib/adapters/xhr.js:121:66)"[[Prototype]] Error