Nuxt生产环境报错TypeError: Cannot read property 'title' of undefined求助
Hey there! Let’s dig into why you’re hitting that TypeError: Cannot read property 'title' of undefined in production when everything works smoothly in development. Here are the most probable culprits and how to fix them:
1. Your error handling might be passing invalid data to posts
Right now, in your asyncData catch block, you’re returning err.response—but if the API request fails (like a 404 or server error), response.data won’t be the post object you expect. This leaves posts as undefined or an error structure, which causes the title access error.
Fix: Rewrite the asyncData to only assign valid post data on success, and return a safe fallback on failure:
async asyncData({ app, params, error }) { const { id } = params; try { const response = await axios.get(`https://hogehoge.com/api/v1/posts/${id}`); // Parse the response only when the request succeeds const posts = JSON.parse(response.data); return { posts }; } catch (err) { // Show a proper error page error({ statusCode: err.response?.status || 500, message: err.response?.data?.message || 'Failed to load the post', }); // Return a fallback to avoid undefined errors return { posts: null }; } }
2. Production API response structure might differ from development
Rails APIs sometimes wrap responses differently in production (like using a root key for serialized data). For example, in dev you might get {"title": "My Post"}, but production returns {"post": {"title": "My Post"}}. If you’re parsing the raw response directly, you’ll end up with an object that doesn’t have a title property.
Fix: Check your Rails API logs or log response.data in production to confirm the structure. If there’s a root key, adjust your parsing:
// If response.data is wrapped in a "post" key const posts = JSON.parse(response.data).post;
3. Add safety checks in your template and head method
Even if the request succeeds, it’s smart to add guards against missing data. Use optional chaining (?.) and fallback values to prevent errors when posts is undefined or null.
Template fix:
<div class="contents-header"> <h1>{{ posts?.title || 'Untitled Post' }}</h1> </div>
Head method fix:
head() { return { title: this.posts?.title || 'My Media Site', meta: [{ hid: 'title', name: 'title', content: this.posts?.title || 'My Media Site' }] } }
4. Double-check your axios configuration for production
If you’re using Nuxt’s axios module, make sure your production baseURL is correctly set in nuxt.config.js. A typo in the production API URL could cause the request to fail silently.
Example nuxt.config.js setup:
export default { modules: ['@nuxtjs/axios'], axios: { baseURL: process.env.NODE_ENV === 'production' ? 'https://hogehoge.com/api/v1' : 'http://localhost:3000/api/v1' } }
内容的提问来源于stack exchange,提问作者Piesuke

