-1

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
Yaroslavm
  • 1,762
  • 2
  • 7
  • 15
william
  • 1
  • 1
  • 1
    how are you authenticating? I dont see any auth headers attached in post request. – Ravi Yadav Aug 30 '23 at 03:54
  • I’m using clerk.import { authMiddleware } from "@clerk/nextjs"; export default authMiddleware({ publicRoutes: ["/", "/api/conversation"], });export const config = { matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"], };"use client"; – william Aug 30 '23 at 05:29
  • maybe it’s the clerk problem – william Aug 30 '23 at 06:41
  • Could you also share your backend code for this api – Ravi Yadav Aug 30 '23 at 06:59
  • actually I don’t know which part is the backend code for this api,I post the github link here,https://github.com/william3333/next13-ai-saas,maybe you can find it in middleware.ts or in the app file – william Aug 30 '23 at 07:21
  • The request to /api/conversation is being redirected because there is no signed-in user, and the path is not included in ignoredRoutes or publicRoutes. To prevent this behavior, choose one of:To make the route accessible to both signed in and signed out users, add "/api/conversation" to the publicRoutes array passed to authMiddleware To prevent Clerk authentication from running at all, pass ignoredRoutes: ["/((?!api|trpc))(_next|.+..+)(.*)", "/api/conversation"] to authMiddleware Pass a custom afterAuth to authMiddleware – william Aug 31 '23 at 08:34
  • , and replace Clerk's default behavior of redirecting unless a route is included in publicRoutes. import { authMiddleware } from "@clerk/nextjs"; // This example protects all routes including api/trpc routes // Please edit this to allow other routes to be public as needed. // See https://clerk.com/docs/references/nextjs/auth-middleware for m export default authMiddleware({ publicRoutes: ["/"] }); export const config = { matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"], }; – william Aug 31 '23 at 08:34
  • AxiosError {message: 'Request failed with status code 500', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', config: {…}, request: XMLHttpRequest, …}code: "ERR_BAD_RESPONSE"config: {transitional: {…}, adapter: 'xhr', transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}message: "Request failed with status code 500"name: "AxiosError"request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}response: {data: 'Internal error', status: 500, statusText: 'Internal Server Error', – william Sep 02 '23 at 15:00

0 Answers0