Reputation: 59
Inside my components I can use axios calls like this normally
let response = await this.$axios.get("api/test")
but inside serverInit
I get a 404 error
async nuxtServerInit({ commit, state }, { $axios }) {
let x = await $axios.$get("api/test")
}
The error is:
Request failed with status code 404
* @param {Object} [request] The request.
* @param {Object} [response] The response.
* @returns {Error} The created error.
*/
module.exports = function createError(message, config, code, request, response) {
var error = new Error(message);
return enhanceError(error, config, code, request, response);
};
it only works if I use the full path
async nuxtServerInit({ commit, state }, { $axios }) {
let x = await $axios.$get("http://localhost:3000/api/test")
}
I'm using express with Nuxt with default axios configs comes with nuxt.
inside nuxt.config.js
axios: {
baseURL: "http://example.com",
browserBaseURL: "http://localhost:3000"
},
serverMiddleware: [{ path: "/api", handler: "~/api/index.js" }],
this is my index.js
inside API folder
const express = require("express");
const router = require("../api/routes/routesIndex");
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
port = process.env.PORT || 3000;
app.use(router);
module.exports = app;
Ff I use full path it will be problem when I host the website, is there something I'm missing to make it work normally?
Upvotes: 1
Views: 610
Reputation: 6909
nuxtServerInit
is only used server side, so it uses baseUrl
instead of browserBaseUrl
.
So it hit http://example.com/api/test, not your localhost nuxt server!
EDIT: Replying to your question in comments.
When hosted, the server still see itself as localhost. I think the only thing that will change will be the port. As it's only run server side, you can it on localhost
.
But be careful with browserBaseUrl
, this one has to hit the correct domain name :)
Upvotes: 1