0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【メモ】自分のQiita記事のURL取得して、ポートフォリオに載せたい!

Last updated at Posted at 2023-10-09

やりたくなった理由

  • MERNでの開発方法のチュートリアルをUdemyで見て少し触った。
  • Expressで自作も含めてAPIを管理したい。
  • Udemyの中でaxiosを使っていたので、実験。
  • Qiitaの記事をポートフォリオサイトに載せてみたい。

実際にやったこと

1. Express,Reactのセットアップをそれぞれする。+ axiosも!
2. QiitaのAPIをつくる。=> .envにぶちこみ
3. 仮server.jsを作り書き込む


require('dotenv').config();
const express = require('express');
const cors = require('cors');
const axios = require('axios');

const app = express();
app.use(cors());

const port = 5000;

app.get('/fetch-qiita-articles', async (req, res) => {
    try {
        const response = await axios.get('https://qiita.com/api/v2/users/mabupro/items', {
            headers: {
                Authorization: `Bearer ${process.env.QIITA_API_TOKEN}`
            }
        });
        res.send(response.data.map(article => ({
            title: article.title,
            url: article.url,
            id: article.id,
            tags: article.tags,
        })));
    } catch (error) {
        console.error('Error fetching data from Qiita API:', error.response?.data || error.message);
        res.status(500).send({ error: 'Internal Server Error' });
    }
});

app.listen(5000, () => console.log(`Server is running on port ${port}`));

4. 次はreact側のsrcのcoponentsフォルダを作って、適当に名前を付けたjsxファイルを作成して
5. App.jsにserver.jsで指定した/fetch-qiita-articlesからaxiosで、server.jsで選んでおいたデータを取ってくる。


import React, { useEffect, useState } from 'react';
import axios from 'axios';
import './App.css';
import FetchQiitaMyArticles from './components/FetchQiitaMyArticles';

function App() {
  const [articles, setArticles] = useState([]);

  useEffect(() => {
    axios.get('http://localhost:5000/fetch-qiita-articles')
      .then(response => setArticles(response.data))
      .catch(error => console.error('Error fetching data: ', error));
  }, []);

  return (
    <div className="App">
      <FetchQiitaMyArticles articles={articles} />
    </div>
  );
}

export default App;

6. 適当に装飾して完成(chatGPTに今回はMaterial-UIで適当に装飾を頼んだ。)


import React from 'react';
import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent';
import CardActionArea from '@mui/material/CardActionArea';
import Typography from '@mui/material/Typography';
import Grid from '@mui/material/Grid';
import Container from '@mui/material/Container';
import Chip from '@mui/material/Chip';
import Box from '@mui/material/Box';

const FetchQiitaMyArticles = ({ articles }) => {
    return (
        <Container maxWidth="sm">
            <Grid container spacing={3}>
                {articles.map(article => (
                    <Grid item xs={12} key={article.id}>
                        <Card sx={{ maxWidth: 600 }} >
                            <CardActionArea
                                href={article.url}
                                target="_blank"
                                sx={{
                                    height: '100%',
                                    display: 'flex',
                                    flexDirection: 'column',
                                    justifyContent: 'space-between'
                                }}
                            >
                                <CardContent sx={{ paddingBottom: 0 }}> 
                                    <Typography
                                        gutterBottom
                                        variant="h6"
                                        component="div"
                                        sx={{
                                            color: 'darkslateblue',
                                            fontWeight: 'bold',
                                            overflow: 'hidden',
                                            textOverflow: 'ellipsis',
                                            display: '-webkit-box',
                                            WebkitLineClamp: 1,
                                            WebkitBoxOrient: 'vertical',
                                            marginBottom: 1,
                                        }}
                                    >
                                        {article.title}
                                    </Typography>
                                </CardContent>
                                <Box sx={{ p: 1 }}>
                                    {article.tags.map((tag) => (
                                        <Chip
                                            label={tag.name}
                                            key={tag.name}
                                            sx={{
                                                marginRight: 1,
                                                marginBottom: 1,
                                                textTransform: 'capitalize',
                                                backgroundColor: '#e0f2f1',
                                                color: '#004d40'
                                            }}
                                        />
                                    ))}
                                </Box>
                            </CardActionArea>
                        </Card>
                    </Grid>
                ))}
            </Grid>
        </Container>
    );
}

export default FetchQiitaMyArticles;

完成品

sever-5000.PNG

app-3000.PNG

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?