Reputation: 615
I'm trying to use Express as a backend running a VueJS web application with hot reload, but I can't FETCH
the content from the server.
vue.config.js:
module.exports = {
devServer: {
proxy: 'http://localhost:3000'
}
}
server.js:
const express = require('express');
const app = express();
const port = 3000
app.get('/hello', (req, res) => {
res.send({ "message": "Hello World" }) //Content
});
app.listen(port, () => {
console.log(`WebServer listening at port`);
});
That is running and /hello
is working at port 3000.
Now, I'm starting both this way:
npm run server & nodemon server.js
Trying to fetch /hello
in the Vue application, but it's not working. Am I missing anything?
<template>
<div class="flex-col">{{tasks}}
</div>
</template>
<script>
export default {
name:"ListToDo",
data(){
return{
tasks: []
}
},
methods:{
FETCH: function(){
fetch("/tasks/")
.then(res => res.json())
.then(data => this.tasks=data)
}
},
mount(){
this.FETCH()
}
}
Upvotes: 0
Views: 440
Reputation: 138266
The front-end is fetching /tasks
, but the server does not have a route for /tasks
, so it will respond with 404 Not Found
.
One solution is to add a route for /tasks
to your server's Express instance:
app.get('/tasks:myOptions(/*)?', (req, res) => {
res.send({ message: 'tasks', myOptions: req.params.myOptions })
})
Or you can update your component to use the /hello
route already setup in the server:
export default {
methods: {
FETCH: function() {
fetch("/hello") 👈
.then(res => res.json())
.then(data => this.tasks=data)
}
}
}
}
If you prefer to keep your original /hello
route while using /tasks
from the client, the path will need to be rewritten client-side through the proxy, using the pathRewrite
config shown below. However, this can't be done with the simple string proxy config, and specific route contexts (i.e., /tasks
) must be specified:
// vue.config.js
module.exports = {
devServer: {
proxy: {
'/tasks': {
target: 'http://localhost:3000',
pathRewrite: { '^/tasks' : '/hello' }
}
}
}
}
Upvotes: 1