Nodejs + Express get 405 Not Allowed

66 Views Asked by At

I'm trying to make a node js site that generates keys for my outlinevpn, the main bug is that when I try to generate a key, it goes into the outline database but won't show it on the site.

Constant error: Error: Request failed with status code 405

Response data: { code: 'MethodNotAllowed', message: 'GET is not allowed' }

Response status: 405

My site uses nginx and I have a ssl certificate from cloudflare installed.

app.js:
const express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios');
const https = require('https');

const app = express();
const PORT = 3000;

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

const API_URL = 'secret';

const axiosInstance = axios.create({
  httpsAgent: new https.Agent({
    rejectUnauthorized: false
  })
});

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

app.post('/generate-key', async (req, res) => {
  const userName = req.body.username;

  try {
    // Step 1: Create an access key
    const createKeyResponse = await axiosInstance.post(`${API_URL}/access-keys`, null, { headers: { 'Content-Type': 'application/json' } });
    const keyId = createKeyResponse.data.id;

    // Step 2: Rename the access key
    await axiosInstance.put(`${API_URL}/access-keys/${keyId}/name`, { name: userName });

    // Step 3: Retrieve the updated access key using the same endpoint
    const getKeyResponse = await axiosInstance.get(`${API_URL}/access-keys/${keyId}`);
    const generatedKey = getKeyResponse.data.secret;

    // Send the generated key as JSON response
    res.json({ accessKey: generatedKey });
  } catch (error) {
    console.error('Error:', error.message);
    console.error('Response data:', error.response && error.response.data);
    console.error('Response status:', error.response && error.response.status);
    res.status(500).json({ error: 'Internal Server Error' });
  }
});

app.listen(PORT, () => {
  console.log(`Server is runnning on http://localhost:${PORT}`);
});
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Access Key Generator</title>
</head>
<body>
  <h1>Access Key Generator</h1>
  <form id="generateKeyForm">
    <label for="username">Enter your name:</label>
    <input type="text" id="username" name="username" required>
    <button type="button" onclick="generateAccessKey()">Generate Access Key</button>
  </form>

  <div id="result" style="margin-top: 20px;"></div>

  <script>
    async function generateAccessKey() {
      const username = document.getElementById('username').value;

      try {
        const response = await fetch('/generate-key', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ username }),
        });

        const data = await response.json();

        if (response.ok) {
          document.getElementById('result').innerHTML = `Your access key: ${data.accessKey}`;
        } else {
          document.getElementById('result').innerHTML = `Error: ${data.error}`;
        }
      } catch (error) {
        console.error('Error:', error.message);
        document.getElementById('result').innerHTML = 'Internal Server Error';
      }
    }
  </script>
</body>
</html>

I still don't understand how to fix this problem.

0

There are 0 best solutions below