Hello everyone I am extremely new at the Next.js world.
I am using the getStaticProps() to make an API call and in order to make it little organized, i have created a separate page "git" under "pages" folder and here is my code:
function Git({ stars }) {
return <div>Next stars: {stars}</div>
}
export async function getStaticProps() {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const json = await res.json()
return { stars: json.stargazers_count }
}
export default Git
And i am trying to load the API data to the index.js file under the "pages" folder.
Inside the index.js file, i am using below to load the API data from the "Git" page
import fetch from "isomorphic-unfetch"
import Git from './Git'
And under the following
render () {
return (
<Git />
On the browser, i am not seeing the API data but i am seeing the HTML from the "Git" page
<div>Next stars: </div>
Is there any way if i can load the API data from different page to the index.js page?
However, if i directly access the page for example: http://0.0.0.0:3000/Git then i get the proper API data.
Issue
The issue is about the API data in the page "Git" is not getting passed to the main page "index.js" is there any way if i can pass the data from the "Git" to the "index.js"
I resolved it by putting the following code in the index.js file
const gitData = await Git.getInitialProps();
And that's where I want to print it out
<Git {...this.props.gitData}/>
Related
I have a test API under: pages\api\accounts\login.js. And I am learning the new app folder, which is still an experimental feature in Next.js (as of today).
Is it possible to move my login script into the app folder? I tried moving/renaming to app\api\accounts\login\pages.js, but when I do this:
async function handler(req, res) {
console.log(res);
}
export default handler;
I use the URL: http://localhost:3000/api/accounts/login. I get:
Server Error
Error: Cannot find module for page: /api/accounts/login
I also tried moving it to: app/api/accounts/login/page.js. But I get the same error.
As you can read on the API Routes page of the new documentation of Next.js, API routes are currently as before, meaning they should be in the pages/api folder:
API routes should still be defined in the pages/api/* directory and not moved to the app directory.
We are considering what API routes would look like in the app directory and will update this page in the future.
Some use cases where an API route was used to keep access tokens secure when calling an external API from the client can now be done directly in Server Components.
Any file inside the folder pages/api is mapped to /api/* and will be treated as an API endpoint instead of a route.
For example, the following API route pages/api/user.ts returns a json response with a status code of 200:
// pages/api/user.ts
import { NextApiRequest, NextApiResponse } from 'next'
export default function handler(req: NextApiRequest, res: NextApiResponse) {
res.status(200).json({ name: 'John Doe' })
}
I'm using the glob import functionality of Vite to bring in multiple markdown files to a SvelteKit page:
<script context="module">
export async function load() {
const employmentsMeta =
import.meta.globEager('./employments/*.md');
return {
props: {
employmentsMeta: employmentsMeta
}
};
}
</script>
<script>
export let employmentsMeta;
</script>
This works well for me to access the metadata via employmentsMeta[Object.keys(employmentsMeta)[0]]['metadata']. I'm having difficulty accessing the actual contents of the markdown file, however - no matter how I attempt to access it, it seems to be coming back as undefined.
For example, console.log(employmentsMeta[Object.keys(employmentsMeta)[0]['default']]) returns undefined, despite my understanding that there's a default export object in there, and the metadata access working as intended.
How do I access the payload / body of the imported markdown?
I have a similar use-case, with markdown files in SvelteKit as blog posts.
In your example, I'd get the file contents as html like this:
const contents = employmentsMeta[Object.keys(employmentsMeta)[0]].default.render();
contents here is an object like this:
{
html: '/* a string with the markdown content parsed as html */',
css: { code: '', map: null },
head: '',
}
I guess you have to use mdsvex for the md->html conversion to happen.
EDIT: I should mention that I do this in an endpoint ([slug].json.js), return the results, and get them in the route, as doing it in the load function was throwing an error (...default.render is not a function) client-side.
I want to fetch files from another server (e.g. a CDN) with the #nuxtjs/content module so that the .md files can be managed independently without Nuxt.js.
My current nuxt.config.js file looks like this:
export default {
...
content: {
dir: 'http://some-cdn.xyz/content/'
},
...
}
Now I want to load the content in the pages/_slug.vue file:
<template>
<div>
<NuxtContent :document="doc" />
</div>
</template>
<script>
export default {
async asyncData({ $content, params }) {
const doc = await $content(params.slug || 'index').fetch();
return { doc };
},
};
</script>
Now when I type in http://localhost:3000/some-page, I should get the corresponding file (some-page.md) from the CDN. Instead, I get this error from Nuxt.js: /some-page not found.
What should I do to get it working and is this even possible with my current setup?
As told here: https://github.com/nuxt/content/issues/237
This is not doable with the content module and is not planned to be done neither. A solution would be to manually fetch the files during the build time or alike.
You can maybe get some inspiration from this comment: https://github.com/nuxt/content/issues/37#issuecomment-664331854 or use another markdown parser.
Since #nuxtjs/content can't fetch files from another server, I used the marked.js library instead.
I'm trying to write a basic local api for myself using Next.js, it is a timeline generator, and I am stuck at actually reading the file from the api folder.
What do I want in my local aplication:
1.A simple page where I can input an event, with a date and description
2.Open a list.json file somewhere and push that new event to that json file, writing on it.
What I am currently doing and where I am stuck:
I am aware we cant write on files on the client side, so I started looking at the api routes in next js to access the JSON file, but I cannot even manage to read it!
I have an api folder inside pages folder, and in this api folder I have two files: one is the list.json file, where I previously manually write some events with respective dates; and the other is getlist.js, with this code:
var fs = require('fs');
export default function getList(req, res) {
const rawList = fs.readFile('list.json');
var list = JSON.parse(rawList);
res.json(list);
}
Now on the pages folder I have a index.js file where I try to access this getlist.js api using getStaticProps(), like this:
import getlist from './api/getlist'
export async function getStaticProps(){
var list = getlist();
return {
props: {
list
}
}
}
I have tried using other stuff, like the fecth function, to get to getlist.js, but nothing I do seems to work.
Can anyone help me?
And since I'm already in here, how would I manage to get the input from the form I already have in my client side page and write it to that list.json file in my api folder?
There are two ways how you can read json in next.js:
Import inside getStaticProps [https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation]
export async function getStaticProps(context){
const example = await import('./api/example.json');
return {props: {example: example.default}}
}
Import or read in handler function inside api folder [https://nextjs.org/docs/api-routes/introduction]:
const fs = require('fs');
export default async function handler (req, res) {
const example = await fs.readFile('./example.json');
return res.status(200).json({example});
}
In order to write *.json file you need to send request with value to the server api (handler from api folder that was mentioned before).
That's how the part to write json will look like:
const fs = require('fs');
export default async function handler(req, res) {
//...
if (req.method === 'POST'){
fs.writeFileSync('./example.json', JSON.stringify(req.body))
return res.status(200).json({});
}
//...
}
I have been trying loading a local json file present in my project folder of Angular 2 using http get method. Look at the following example code snippet:
private _productURL = 'api/products/products.json';
getProducts(): Observable<any> {
return this._http.get(this._productURL).map((response : Response) => <IProduct[]> response.json())
.do(data =>console.log(JSON.stringify(data))).catch(this.handleError);
}
Now when I'm trying to load it with internet connected, it's working. But when I'm turing on the offline checkbox from the browser developer options(https://developers.google.com/web/tools/chrome-devtools/network-performance/reference#offline), the json stops loading again. It starts showing me error in console about No internet connection and doesn't load anything.
Is there any other way to do this? or using http get..how to do it?
You can import a json file if you do as follows:
create a json-typings.d.ts file with:
declare module "*.json" {
const value: any;
export default value;
}
this is a wildcard module definition that allows us to import non javascript files in this case JSON files.
you should now be able to import json files to your project:
import * as products from "./products.json";