"AxiosError" netlify 404 - React + Node.js

I made a URL Shortener using node.js on the back end and react js on the front end.

It works normally locally, however, when deploying and setting the environment variables the code does not work.

Front-End :
import React, { useState } from ‘react’;
import axios from ‘axios’;
import { Form, Button, Alert } from ‘react-bootstrap’;
import ‘./App.css’;

const App = () => {
const [originalUrl, setOriginalUrl] = useState(‘’);
const [shortenedUrl, setShortenedUrl] = useState(‘’);
const [errorMessage, setErrorMessage] = useState(‘’);
const [loading, setLoading] = useState(false);

const apiUrl = process.env.REACT_APP_BACKEND_URL || ‘http://localhost:5000’;

const handleError = (error, defaultMessage) => {
console.error(‘Erro:’, error);
setErrorMessage(defaultMessage);
setShortenedUrl(‘’);
};

const shortenUrl = async () => {
try {
setLoading(true);
console.log(‘Enviando requisição para encurtar URL:’, originalUrl);
const response = await axios.post(${apiUrl}/shorten, { originalUrl });
console.log(‘Resposta recebida:’, response.data);
setShortenedUrl(response.data.shortUrl);
setErrorMessage(‘’);
} catch (error) {
handleError(error, ‘Ocorreu um erro ao encurtar a URL. Tente novamente.’);
} finally {
setLoading(false);
}
};

return (



Encurtador de Link




<Form.Group controlId=“formOriginalUrl” className=‘form-url-original’>
<Form.Label className=‘text-url’>Insira o Link Original</Form.Label>
<Form.Control
className=‘input’
type=“url”
placeholder=“Digite o Link original”
value={originalUrl}
onChange={(e) => setOriginalUrl(e.target.value)}
/>
</Form.Group>

    <Button variant="primary" className='btn-url-original' onClick={shortenUrl} disabled={loading}>
      {loading ? 'Aguarde...' : 'Encurtar Link'}
    </Button>
  </Form>

  {errorMessage && <Alert variant="danger" className="mt-3 new-url">{errorMessage}</Alert>}

  {shortenedUrl && !errorMessage && (
    <div className="mt-3 new-url">
      <p>Seu Novo Link</p>
      <a href={shortenedUrl} target="_blank" rel="noopener noreferrer">
        {shortenedUrl}
      </a>
    </div>
  )}
</div>

);
};

export default App;

Back-end :
const express = require(‘express’);
const shortid = require(‘shortid’);
const cors = require(‘cors’);
const app = express();
const PORT = 5000;
require(‘dotenv’).config();
const urlDatabase = {};

const corsOptions = {
origin: ‘*’,
methods: ‘GET,HEAD,PUT,PATCH,POST,DELETE’,
credentials: true,
optionsSuccessStatus: 204,
};

app.use(cors(corsOptions));
app.use(express.json());

app.post(‘/shorten’, (req, res) => {
try {
const { originalUrl } = req.body;
const shortCode = shortid.generate();
const shortUrl = ${process.env.BACKEND_URL}/${shortCode};

console.log('URL original:', originalUrl);
console.log('Código curto gerado:', shortCode);

urlDatabase[shortCode] = originalUrl;

res.json({ shortUrl });

} catch (error) {
console.error(‘Erro ao encurtar URL:’, error);
res.status(500).json({ error: ‘Ocorreu um erro ao encurtar a URL. Tente novamente.’ });
}
});

app.get(‘/:shortCode’, (req, res) => {
const { shortCode } = req.params;
const originalUrl = urlDatabase[shortCode];

if (originalUrl) {
res.redirect(originalUrl);
} else {
res.status(404).json({ error: ‘URL não encontrada’ });
}
});

app.listen(PORT, () => {
console.log(Servidor rodando em 'http://localhost:${PORT}');
});

// Atualize a função serverless para algo assim (no seu arquivo functions/shorten.js, por exemplo):
exports.handler = async (event, context) => {
try {
const { originalUrl } = JSON.parse(event.body);
const shortCode = shortid.generate();
const shortUrl = ${process.env.BACKEND_URL}/${shortCode};

console.log('URL original:', originalUrl);
console.log('Código curto gerado:', shortCode);

urlDatabase[shortCode] = originalUrl;

return {
  statusCode: 200,
  body: JSON.stringify({ shortUrl }),
};

} catch (error) {
console.error(‘Erro ao encurtar URL:’, error);
return {
statusCode: 500,
body: JSON.stringify({ error: ‘Ocorreu um erro ao encurtar a URL. Tente novamente.’ }),
};
}
};

And the 2 envs are pointing to the backend url https://url-shortner-brasil-back-end.netlify.app](https://url-shortner-brasil-back-end.netlify.app/

Someone can help me please ?

@renanberton Unfortunately your post is very poorly formatted which makes it hard to read.

It also appears to just be a dump of code.

Can you:

  1. Clean up the formatting using fenced code blocks ```
  2. Say exactly what error is occurring

Your repo has several issues: renanberton/url-shortner-backend: Encurtador de Url - Backend (github.com)