0

I'm building a full-stack Web Application and I encounter a few annoying errors. My Code to fetch Data in the .vue File looks like this:

<script>
import { createHydrationRenderer } from 'vue'
import axios, { isCancel, AxiosError } from 'axios'

export default {
    data() {
        return {
            shoppinglistitems: []
        }
    },
async mounted() {
        await axios.get('/shoppinglistitems')
            .then(response => {
                this.shoppinglistitems = response.data
            })
            .catch(error => {
                console.log(error)
                this.shoppinglistitems = []
            })
    },
components: { createHydrationRenderer }
}
</script>

I already created a vue.config.js File to battle the CORS Errors:

module.exports = {
    devServer: {
        proxy: {
            '/api': {
                target: 'http://localhost:8000',
                changeOrigin: true,
                pathRewrite: { '^/api': '' },
            },
        },
    },
}

Lastly, theres parts of the server.js File:

require('dotenv').config()
const cors = require('cors');
const url = process.env.DATABASE_URL || "mongodb://127.0.0.1/projectdb"

const User = require("../src/model/User.js")
const ShoppingListItems = require("./model/ShoppingListItems.js")
const ShoppingList = require("./model/ShoppingList.js")

mongoose.connect(url, {
    useNewUrlParser: true,
    useUnifiedTopology: true
})
    .then(() => {
        console.log('Connected to Database')
        app.listen(8000, () => {
            console.log('Server is listening on port 8000')
        })
    })
    .catch((error) => console.log(error))

app.use(express.json())
app.use(cors())

// Get all Items in Shoppinglist
app.get('/api/shoppinglistitems', async (req, res) => {
    try {
        const shoppinglistitems = await ShoppingListItem.find({})
        res.status(300).json(shoppinglistitems)
        res.send(shoppinglistitems)
    } catch (error) {
        res.status(500).json({ message: error.message })
    }
})

My frontend runs with vite on localhost:5173 Here I get an 404 Error Error in Web Console

When I try to replace the target with await fetch('http://localhost:8000/shoppinglistitems') I'll just get another CORS Error

What I did try was to change the code in the .vue File like this:

async mounted() {
        try {
            const response = await fetch('http://localhost:8000/shoppinglistitems')
            console.log(response)
            const shoppinglistitems = await response.json()
            this.shoppinglistitems = shoppinglistitems
        } catch (error) {
            console.error(error)
        }
    },

Unfortunately this gives me an Error with nodemon running expressjs in the back:

node:internal/errors:490
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:399:5)
    at ServerResponse.setHeader (node:_http_outgoing:645:11)
    at ServerResponse.header (C:\Workspace\project_hslu\node_modules\express\lib\response.js:794:10)
    at ServerResponse.send (C:\Workspace\project_hslu\node_modules\express\lib\response.js:174:12)
    at ServerResponse.json (C:\Workspace\project_hslu\node_modules\express\lib\response.js:278:15)
    at C:\Workspace\project_hslu\src\server.js:101:25
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
}

Node.js v18.16.0

I'm new to all this, so please be kind with me :)

1 Answer 1

1

The first issue ( error in web console) is because, you have routed /api to your backend. So all the calls beginning with /api will route to backend ( port : 8000 ) and other will route to the vue app ( other port - may be 5173 )
Change this url to : /api/shoppinglistitems and this will hit the backend.

Regarding second issue, the error is with the node js api code. Please provide the code you wrote for shoppinglistitems api.

6
  • Hi @sachin, thanks for your help. With the /api route you probably mean the one specified in the vue.config.js File. If I change the url in my Dashboard.vue File to await axios.get('/api/shoppinglistitems') , I will still get a 404 GET Error for http://localhost:5173/api/shoppinglistitems. It looks like it doesn't route to the backend with port: 8000. I also found out, that the second issue also happens in postman, as soon as I get or post data. Unfortunately I'm not quite sure which code you need. Is it parts of the server.js? I only have a ShoppingListItem.js in /model with the schema
    – WoodPecker
    Commented May 11, 2023 at 20:43
  • Yes I need server.js file
    – sachin
    Commented May 12, 2023 at 4:30
  • And try changing the /api to /api/* in vue.config.js file
    – sachin
    Commented May 12, 2023 at 4:31
  • Changing the /api to /api/* didn't help, but when I use the full path in the .vue File like this const response = await fetch('http://localhost:8000/api/shoppinglistitems') , it does work which is weird. I expanded my main post with the necessary info in server.js, but I already found the mistake. The problem happens in the catch(error) line. After deleting this, it works. If you have any suggestions on how to make the code "better", feel free. Other than that, do you think using the full path in .vue is the "proper" solution?
    – WoodPecker
    Commented May 12, 2023 at 7:12
  • instead of const shoppinglistitems = await ShoppingListItem.find({}) res.status(300).json(shoppinglistitems) res.send(shoppinglistitems) Try with const shoppinglistitems = await ShoppingListItem.find({}) res.send(shoppinglistitems)
    – sachin
    Commented May 12, 2023 at 8:17

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.