部署我的网络应用程序,无法获取提交按钮来回发和查询我的数据库

问题描述 投票:0回答:1

我正在构建一个图书推荐引擎。我有一个主页、测验页面和推荐页面。我已将此代码部署到 AWS S3 存储桶,但无法让测验提交按钮实际正常工作。我有一个 postgres 数据库,并且希望查询该数据库,以根据问题值的类型 ID 映射来获取随机书籍推荐。

尽管尝试使用 server.js 代码来处理提交 post 方法,但当我单击提交按钮时,我收到“方法不允许”错误。我不知道从这里该去哪里。

这是我的 quiz.js 代码:

`const { Client } = require('pg');

const dbConfig = {
    user: 'username',
    host: 'host',
    database: 'postgres',
    password: 'password',
    port: 5432, 
    ssl: {
        rejectUnauthorized: false 
    }
};

const cors = require('cors');
app.use(cors());

const client = new Client(dbConfig);


client.connect()
    .then(() => {
        console.log('Connected to the database');
        startQuiz();
    })
    .catch(error => {
        console.error('Error connecting to the database:', error);
    });

process.on('exit', () => {
    client.end();
});

const genreIdMapping = {
    7: 3,
    8: 3,
    9: 6,
    10: 6,
    11: 8,
    12: 8,
    13: 7,
    14: 4,
    15: 1,
    16: 9,
    17: 9,
    18: 10,
    19: 10,
    20: 2,
    21: 5
};

function startQuiz() {
    console.log('Quiz form loaded');
    const quizForm = document.getElementById('quiz-form');

    quizForm.addEventListener('submit', (event) => {
        event.preventDefault();
        console.log('Quiz form submitted');

        let totalScore = 0;
        const userScores = {};

        for (let i = 1; i <= 7; i++) {
            const selectedAnswerIndex = parseInt(document.querySelector(`input[name="answer${i}"]:checked`).value);
            totalScore += questions[i - 1].answers[selectedAnswerIndex].score;
            userScores[i - 1] = questions[i - 1].answers[selectedAnswerIndex].score;
        }

        const genreId = genreIdMapping[totalScore];
        if (genreId) {
            fetch('https://mhtwcqy8pd.execute-api.us-east-2.amazonaws.com/BookWizard', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ genreId })
            })
            
            .then(response => response.json())
            .then(data => {
                let resultText = '';
                if (data.title) {
                    resultText = `
                        <h2>Based on your answers, we recommend the following book:</h2>
                        <p>${data.title} by ${data.author}</p>
                    `;
                } else {
                    resultText = "No book recommendation found for your score.";
                }
                const resultContainer = document.getElementById('result-container');
                resultContainer.innerHTML = resultText;
            })
            .catch(error => {
                console.error('Error fetching book recommendation:', error);
                const resultContainer = document.getElementById('result-container');
                resultContainer.innerHTML = "Error fetching book recommendation.";
            });
        } else {
            console.log("No genre ID mapping found for your score.");
            const resultContainer = document.getElementById('result-container');
            resultContainer.innerHTML = "No genre ID mapping found for your score.";
        }
    });
}

document.addEventListener('DOMContentLoaded', () => {
    console.log('Document loaded');
    startQuiz();
});`

这是我的 server.js 代码:

`import { Client } from 'pg';
import express from 'express';
import { urlencoded, json } from 'body-parser';

const app = express();
const port = 3000;
const cors = require('cors');
app.use(cors());

const dbConfig = {
    user: 'postgres',
    host: 'host',
    database: 'database',
    password: 'password',
    port: 5432, 
    ssl: {
        rejectUnauthorized: false 
    }
};

const client = new Client(dbConfig);

client.connect()
    .then(() => {
        console.log('Connected to the database');
    })
    .catch(error => {
        console.error('Error connecting to the database:', error);
    });

app.use(urlencoded({ extended: false }));
app.use(json());
app.use(express.static('public'));

app.post('/recommendation', async (req, res) => {
    try {
        const { genreId } = req.body;

        const query = 'SELECT title, author, description, imgurl FROM books WHERE genreId = $1 ORDER BY RANDOM() LIMIT 1';
        const { rows } = await client.query(query, [genreId]);

        if (rows.length > 0) {
            const recommendation = {
                title: rows[0].title,
                author: rows[0].author
                description: rows[0].description
                imgurl: rows[0].imgurl

            };
            res.json(recommendation);
        } else {
            res.json({ message: 'No book recommendation found for this genre' });
        }
    } catch (error) {
        console.error('Error fetching book recommendation:', error);
        res.status(500).json({ message: 'Error fetching book recommendation' });
    }
});

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
});`

我已经尝试了上面的代码,并尝试在单击提交按钮时获得结果。实际结果是方法不允许错误。

javascript html amazon-web-services post submit
1个回答
0
投票

您没有说您是在服务器日志还是客户端日志上收到错误,但我假设您在客户端日志中收到错误。它甚至可能是 CORS 问题,但可能是您的 S3 中设置了不允许发帖的问题。

由于您没有在正文中发送复杂的 json,因此您可以尝试将其切换为 GET,并将 GenreId 作为参数附加到 url 末尾,或将其作为查询字符串项包含在内。

fetch(`https://mhtwcqy8pd.execute-api.us-east-2.amazonaws.com/BookWizard/${genreId}`, 
       {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            },
            // body: JSON.stringify({ genreId })
        })

如果是 body 参数或 POST 方法的问题(当亚马逊通过资源配置不允许 POSTS 时,将允许 GET)

这并不是一个完整的答案,但它可能会引导您找到一些演绎的故障排除步骤。

© www.soinside.com 2019 - 2024. All rights reserved.