为什么 useFetch 在向 api 发出请求后返回 HTML 而不是 JSON 对象?

问题描述 投票:0回答:1

我正在向 API 路由发出请求,并且 useFetch() 方法返回 HTML 而不是 JSON。我尝试注释掉代码块并手动逐步测试所有内容,但无济于事。我做错了什么吗? API 路由位于 server/api/auth.ts 内

const { data } = await useFetch('/api/auth/exists/email', {
    query: {
        email_address: enteredEmail.value
    }, 
    baseURL: '/api/auth/exists/email',
    onResponseError: ({error}) => {
        console.error(error);
        registrationErrors.email.push('An unexpected error has occurred.')
    }
});

作为回报,我收到这个:

RESPONSE:  <!DOCTYPE html>
<html >
<head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"><link rel="preload" as="style" href="/_nuxt/node_modules/@fortawesome/fontawesome-svg-core/styles.css"><link rel="preload" as="style" href="/_nuxt/node_modules/@vueform/multiselect/themes/default.css"><link rel="preload" as="style" href="/_nuxt/node_modules/animate.css/animate.min.css"><link rel="preload" as="style" href="/_nuxt/node_modules/@vueform/toggle/themes/default.css"><link rel="preload" as="style" href="/_nuxt/node_modules/.cache/nuxt-google-fonts/css/nuxt-google-fonts.css"><link rel="preload" as="style" href="/_nuxt/node_modules/vite-plugin-vue-inspector/src/Overlay.vue?vue&type=style&index=0&scoped=31d1379f&lang.css"><link rel="preload" as="style" href="/_nuxt/components/AppHeader.vue?vue&type=style&index=0&lang.scss"><link rel="preload" as="style" href="/_nuxt/components/AuthModal.vue?vue&type=style&index=0&scoped=ff55f906&lang.scss"><link rel="preload" as="style" href="/_nuxt/components/Modal.vue?vue&type=style&index=0&scoped=0b5a066a&lang.scss"><link rel="preload" as="style" href="/_nuxt/components/FormGroup.vue?vue&type=style&index=0&scoped=6b1d710f&lang.scss"><link rel="preload" as="style" href="/_nuxt/components/ErrorBox.vue?vue&type=style&index=0&scoped=c34b980e&lang.scss"><link rel="preload" as="style" href="/_nuxt/components/TextInput.vue?vue&type=style&index=0&scoped=4f98be6b&lang.scss"><link rel="preload" as="style" href="/_nuxt/components/Checkbox.vue?vue&type=style&index=0&scoped=84f5ff5b&lang.scss"><link rel="preload" as="style" href="/_nuxt/components/ButtonPrimary.vue?vue&type=style&index=0&scoped=fcc59362&lang.scss"><link rel="preload" as="style" href="/_nuxt/components/AppHeaderSubMenu.vue?vue&type=style&index=0&lang.scss"><link rel="modulepreload" as="script" crossorigin href="/_nuxt/Users/hayden/Desktop/k_discuss/node_modules/nuxt/dist/app/entry.js"><link rel="stylesheet" href="/_nuxt/node_modules/@fortawesome/fontawesome-svg-core/styles.css"><link rel="stylesheet" href="/_nuxt/node_modules/@vueform/multiselect/themes/default.css"><link rel="stylesheet" href="/_nuxt/node_modules/animate.css/animate.min.css"><link rel="stylesheet" href="/_nuxt/node_modules/@vueform/toggle/themes/default.css"><link rel="stylesheet" href="/_nuxt/node_modules/.cache/nuxt-google-fonts/css/nuxt-google-fonts.css"><link rel="stylesheet" href="/_nuxt/node_modules/vite-plugin-vue-inspector/src/Overlay.vue?vue&type=style&index=0&scoped=31d1379f&lang.css"><link rel="stylesheet" href="/_nuxt/components/AppHeader.vue?vue&type=style&index=0&lang.scss"><link rel="stylesheet" href="/_nuxt/components/AuthModal.vue?vue&type=style&index=0&scoped=ff55f906&lang.scss"><link rel="stylesheet" href="/_nuxt/components/Modal.vue?vue&type=style&index=0&scoped=0b5a066a&lang.scss"><link rel="stylesheet" href="/_nuxt/components/FormGroup.vue?vue&type=style&index=0&scoped=6b1d710f&lang.scss"><link rel="stylesheet" href="/_nuxt/components/ErrorBox.vue?vue&type=style&index=0&scoped=c34b980e&lang.scss"><link rel="stylesheet" href="/_nuxt/components/TextInput.vue?vue&type=style&index=0&scoped=4f98be6b&lang.scss"><link rel="stylesheet" href="/_nuxt/components/Checkbox.vue?vue&type=style&index=0&scoped=84f5ff5b&lang.scss"><link rel="stylesheet" href="/_nuxt/components/ButtonPrimary.vue?vue&type=style&index=0&scoped=fcc59362&lang.scss"><link rel="stylesheet" href="/_nuxt/components/AppHeaderSubMenu.vue?vue&type=style&index=0&lang.scss"><script>
window.__NUXT_DEVTOOLS_TIME_METRIC__ = window.__NUXT_DEVTOOLS_TIME_METRIC__ || {}
window.__NUXT_DEVTOOLS_TIME_METRIC__.appInit = Date.now()
</script></head>
<body ><div id="__nuxt"><div data-v-inspector="app.vue:2:3"><div data-v-inspector="layouts/default.vue:2:5"><div data-v-inspector="components/AppHeader.vue:2:5"><header class="app-header" data-v-inspector="components/AppHeader.vue:3:9"><img src="/_nuxt/assets/img/kd_logo.png" alt="Knox Discuss Logo" class="logo" data-v-inspector="components/AppHeader.vue:4:13"><button class="login-btn" data-v-inspector="components/AppHeader.vue:5:13"><span></span><span data-v-inspector="components/AppHeader.vue:7:17">Login / Register</span></button></header><!----></div><div class="menu-bar" data-v-inspector="components/AppHeaderSubMenu.vue:2:5"><a class="menu-bar__link" href="#" data-v-inspector="components/AppHeaderSubMenu.vue:3:9"><span></span> Live Feed </a><a class="menu-bar__link" href="#" data-v-inspector="components/AppHeaderSubMenu.vue:9:9"><span></span> Channels </a><a class="menu-bar__link" href="#" data-v-inspector="components/AppHeaderSubMenu.vue:15:9"><span></span> Trending </a></div><!--[--> hi <!--]--></div></div></div><script type="application/json" id="__NUXT_DATA__" data-ssr="true">[["Reactive",1],{"data":2,"state":3,"_errors":6,"serverRendered":7,"path":8,"pinia":9},{},{"$s__nuxt_devtools__":4},{"timeSsrStart":5},1689438997965,{},true,"/api/auth/exists/email",{"modal":10},{"authModalIsOpen":11},["EmptyRef",12],"false"]</script><script>window.__NUXT__={};window.__NUXT__.config={public:{},app:{baseURL:"/",buildAssetsDir:"/_nuxt/",cdnURL:""}}</script><script type="module" src="/_nuxt/@vite/client" crossorigin></script><script type="module" src="/_nuxt/Users/hayden/Desktop/k_discuss/node_modules/nuxt/dist/app/entry.js" crossorigin></script></body>
</html>

这是我的API路线:

router.get('/exists/email', defineEventHandler(event => {

    try{

        const queryParams = getQuery(event);

      /*
        if(!queryParams['email_address']){
            throw new ResponseError({
                status_code: 422, 
                short_msg: 'ERR_MISSING_INFO', 
                body: {
                    message: 'Missing email.'
                }
            });
        }

        const { data } = await $fetch(`${accountAPIUri}/auth/exists/username`, {
            query: {
                email_address: queryParams['email_address']
            }, 
            onResponseError({error}) {
                console.error(error);
            },
        });

        console.log(data.value);
        
        */

        return {
            data: 1234
        };

    }catch(e) {

        return ResponseError.respondWithError(e);

    }

}))

export default useBase('/api/auth', router.handler);

typescript nuxt.js nitro
1个回答
0
投票

这可能是

baseUrl
选项的值存在问题。 您应该检查请求 URL 是否正确。

就我而言,我想请求

http://example.com/api/test
,我写了这样的代码:

const { data } = await useFetch('/api/test', {
    method: 'GET',
    baseURL: 'example.com'
});

我也遇到了同样的问题。

data
中的 HTML 字符串。

我检查了 Chrome DevTools 中的网络面板。

useFetch
正在访问我自己的开发服务器上的页面
http://localhost:13100/example.com/api/test

DevTools view

所以,我在

baseUrl
中添加了URL方案并解决了它。

const { data } = await useFetch('/api/test', {
    method: 'GET',
    baseURL: 'http://example.com'
});

我认为 HTML 字符串是 404 页面的正文,位于

http://localhost:13100/example.com/api/test

© www.soinside.com 2019 - 2024. All rights reserved.