当前位置: 首页 > 知识库问答 >
问题:

如何将XMLHttpRequest发布到节点。js服务器[重复]

都昊乾
2023-03-14

我正在编写一个简单的node js应用程序。

  1. 索引。js
const express = require('express');
const app = express();

require('dotenv').config();

const mysql = require('mysql2');
const connection = mysql.createConnection({
    database: process.env.DB_SCHEMA,
    user: process.env.DB_USER,
    password: process.env.DB_PASS,
    port: process.env.DB_PORT,
    host: process.env.DB_HOST,
});

app.use(express.static('public'));
app.use(express.urlencoded({ extended: true }));
app.set('view engine', 'ejs');

app.get("/", (req, res) => {
    res.render('index');
});


// get topics
// SELECT *  topic ORDER by topic
app.get("/topics", (req,res) => {
    let topics = [];
    connection.query('SELECT *  FROM topic ORDER by topic', (err,results)=>{
        for(let i = 0; i < results.length; i++){
            topics.push(results[i].topic)
        }
        res.render('topic', {
            topics: topics
        });
    });
});

// get categories
// SELECT *  category;
app.get("/topics/:category", (req,res) => {
    let categories = [];
    connection.query('SELECT * FROM category WHERE category.cat_id = (SELECT cat_id FROM topic WHERE  topic.topic = ?)', [req.params.category], (err,results)=>{
        console.log(req.params.category)
        let categories = []
        for(let i = 0; i < results.length; i++){
            categories.push(results[i].category)
        }
        res.render('category', {
            categories: categories,
            topic: req.params.category
        });
    });
});

// get cards
app.get("/topics/:category/:card", (req,res) => {
    let cards = [];
    connection.query('SELECT * FROM card WHERE card.cat_id = (SELECT cat_id FROM category WHERE  category.category = ?)', [req.params.card], (err,results)=>{
        console.log(req.params.card);
        let cards = [];
        for(let i = 0; i < results.length; i++){
            cards.push(results[i])
        }
        console.log(cards);
        res.render('wordmatch', {
            cards: cards,
            category: req.params.category
        });
    });
});

// create a topic
app.post('/topic', (req, res) => {
    console.log("save topic");
    console.log(req.body);
    let id = req.body.id;
    let topic = req.body.topic;
    console.log("id: "+id);
    console.log("topic: "+topic);
    connection.query('INSERT INTO `topic` (`cat_id`,`topic`) VALUES (?,?)', [id, topic], (err, results) => {
        res.redirect('/');
    });
});

// create a category
// EX: INSERT INTO `category` (`cat_id`, `category`) VALUES ('1', 'stoicisim');
app.post('/category', (req, res) => {
    console.log("save category");
    console.log(req.body);
    let id = req.body.id;
    let category = req.body.category;
    console.log("id: "+id);
    console.log("category: "+category);
    connection.query('INSERT INTO `category` (`cat_id`, `category`) VALUES (?, ?)', [id, category], (err, results) => {
        res.redirect('/');
    });
});

// create a card
/* EX: INSERT INTO `card` (`cat_id`, `prompt`, `question`, `answer`) VALUES ('1', 'prompt', 'question','answer');
*/
app.post('/card', (req, res) => {
    console.log("save card");
    console.log(req.body);
    let id = req.body.id;
    let prompt = req.body.prompt;
    let question = req.body.question;
    let answer = req.body.answer;
    console.log("id: "+id);
    console.log("prompt: "+prompt);
    console.log("question: "+question);
    console.log("answer: "+answer);
    connection.query('INSERT INTO `card` (`cat_id`, `prompt`, `question`, `answer`) VALUES (?, ?, ?, ?);', [id, prompt, question, answer], (err, results) => {
        res.redirect('/');
    });
});

app.listen(process.env.PORT || 3000);
<!DOCTYPE html>
<html lang="en">

<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <!-- bootstrap css -->
 <!-- main css -->
 <link rel="stylesheet" href="/static/css/main.css">
 <!-- google fonts -->
 <link href="https://fonts.googleapis.com/css?family=Courgette" rel="stylesheet">
 <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">


 <!-- font awesome -->
 <link rel="stylesheet" href="/css/all.css">
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js " defer></script>
 <title>Flashcard Project</title>
 <style>
 </style>
</head>

<body>

 <div class="container">
  <div class="row">
   <div class="col-11 col-lg-6 my-3">
    <h3 class="text-capitalize">Hacker Meditation Generator</h3>
    <a href="/topics">see topics</a>
    <body>
        <div id="maincontentstyle">
        <div id="boxstyle">
            <div>
            <div id="inputs">
                    <div id="inputBoxes">
                        <title>Input:</title>
                        <div>
                        Topic: <input id= "topic" type="text" value="">
                        </div>
                        <div>
                        ID: <input id= "ID" type="text" value="">
                        </div>   
                        <div>
                        Category: <input id="category" type="text" value="">
                        </div>
                        <div>
                        prompt 1: <input id="pl1" type="text" value=""> 
                        </div>
                        <div>
                        question 1: <input id="ql1" type="text" value=""> 
                        </div>
                        <div>
                        answer 1: <input id="al1" type="text" value=""> 
                        </div>
                    </div>
                    <span style="padding: 3px">
                    <button id ="add_more" class="button" type="button" onClick="add_more()">Add More</button>
                    <button id ="add_more" class="button" type="button" onClick="save()">Save</button>
                    </span>
                </div>
                </div>
            </div>
        </div>
   </div>
  </div>

   </div>

  </div>
 </div>

 




 <!-- jquery -->
 
</body>

</html>
<script type="text/javascript" src="/static/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script>
    var numberOfInputs = 1;

    function add_more() {
    // we've added more inputs.
    addMore = true;

    // set html generated to false, because new inputs have been added.
    htmlGenerated = false;
    
    // increment the number of inputs.
    numberOfInputs++;

    //fetch the input boxes.
    inputs = document.getElementById("inputBoxes");

    // create newline
    br = document.createElement("br");

    //create a new row for a prompt term.
    row0 = document.createElement("div");

    // set the key term text.
    row0.innerHTML = "Prompt ";
    row0.innerHTML +=numberOfInputs;
    row0.innerHTML +=" :";

    // create the input for the prompt.
    key = document.createElement("input");
    key.setAttribute("id","pl"+numberOfInputs);

    //add the key to the row.
    row0.appendChild(key);
    row0.after(br);
    
    //create a new row for a key term.
    row1 = document.createElement("div");

    // set the key term text.
    row1.innerHTML = "Question ";
    row1.innerHTML +=numberOfInputs;
    row1.innerHTML +=" :";

    // create the input for the key.
    key = document.createElement("input");
    key.setAttribute("id","ql"+numberOfInputs);

    //add the key to the row.
    row1.appendChild(key);
    row1.after(br);

    //create a row for the new description.
    row2 = document.createElement("div");

    // set the description text.
    row2.innerHTML = "Answer  "
    row2.innerHTML+=numberOfInputs;
    row2.innerHTML+=" :";
    row2.after(br);

    // create the description input
    description = document.createElement("input");
    description.setAttribute("id","al"+numberOfInputs);

    // add the description to the row.
    row2.appendChild(description);

    // add the rows for the key and the description to the inputBoxes.
    inputs.appendChild(row0);
    inputs.appendChild(row1);
    inputs.appendChild(row2);
    }
</script>
var id;
function init() {
    id = document.getElementById('ID').value;
    console.log("id: "+id);
}

function save(){
    init();
    saveTopic();
    saveCategory();
    saveCard();
}

// save topic
function saveTopic(){
    console.log("save topic");
    //fetch 
    //1. id
    console.log("id: "+id);
    //2. topic
    var topic = document.getElementById('topic').value;
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "http://localhost:3000/topic", true);
    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xhr.onreadystatechange = function()
    {   
        if(xhr.readyState == 4 && xhr.status == 201) {
            console.log(xhr.status)
            console.log("content saved");
        }
        else{
            console.log(xhr.status)
            console.log("content was not save successfully");
        }
    }
    //TODO: send topic
    var json = JSON.stringify({id: id, topic: topic})
    console.log("sending topic"); 
    console.log(json);
    xhr.send(json);
}

// save category
function saveCategory(){
    console.log("save category");
    //1. id
    console.log("id: "+id);
    //2. category
    var category = document.getElementById('category').value;
    console.log("category: "+category);
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "http://localhost:3000/category", true);
    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xhr.onreadystatechange = function()
    {   
        if(xhr.readyState == 4 && xhr.status == 201) {
            console.log(xhr.status)
            console.log("content saved");
        }
        else{
            console.log(xhr.status)
            console.log("content was not save successfully");
        }
    }
    //TODO: send category
    var json = JSON.stringify({id: id, category: category});
    console.log("sending category");
    console.log(json);
    xhr.send(json);
}

// save card
function saveCard(){
    console.log("save card");
    //fetch
    //1. id
    console.log("id: "+id);
    var json = JSON.stringify({id: id});
    // loop for each and append to array
        //2. prompt 
        //3. question
        //4. answer
    //
    var elements = document.getElementsByTagName("input")
    for (var i = 0; i < elements.length; i++) {
        if(elements[i].id.includes("pl")) {
            console.log("prompt: "+ elements[i].value);
            json["prompt"] = elements[i].value;
        }
        if(elements[i].id.includes("al")) {
            console.log("answer: "+ elements[i].value);
            json["answer"] = elements[i].value;
        }
        if(elements[i].id.includes("ql")) {
            console.log("question: "+ elements[i].value);
            json["question"] = elements[i].value;
        }
    }
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "http://localhost:3000/card", true);
    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xhr.onreadystatechange = function()
    {   
        if(xhr.readyState == 4 && xhr.status == 201) {
            console.log(xhr.status)
            console.log("content saved");
        }
        else{
            console.log(xhr.status)
            console.log("content was not save successfully");
        }
    }
    //TODO: send card
    console.log("sending card");
    console.log(json);
    xhr.send(json);
}

预期:请求正文应从服务器注销

实际:

应用程序。js日志

id: 6
app.js:16 save topic
app.js:19 id: 6
app.js:38 sending topic
app.js:39 {"id":"6","topic":"topic"}
app.js:45 save category
app.js:47 id: 6
app.js:50 category: category
app.js:67 sending category
app.js:68 {"id":"6","category":"category"}
app.js:74 save card
app.js:77 id: 6
app.js:87 prompt: prompt 1
app.js:95 question: question 1
app.js:91 answer: answer 1
app.js:114 sending card
app.js:115 {"id":"6"}
app.js:32 200
app.js:33 content was not save successfully
app.js:32 200
app.js:33 content was not save successfully
app.js:32 200
app.js:33 content was not save successfully
app.js:61 200
app.js:62 content was not save successfully
app.js:61 200
app.js:62 content was not save successfully
app.js:61 200
app.js:62 content was not save successfully
app.js:109 200
app.js:110 content was not save successfully
app.js:109 200
app.js:110 content was not save successfully
app.js:109 200
app.js:110 content was not save successfully

指数js日志

save topic
{}
id: undefined
topic: undefined
save category
{}
id: undefined
category: undefined
save card
{}
id: undefined
prompt: undefined
question: undefined
answer: undefined
save topic
{}
id: undefined
topic: undefined
save category
{}
id: undefined
category: undefined
save card
{}
id: undefined
prompt: undefined
question: undefined
answer: undefined

有人能帮我理解我在这里错过了什么吗?非常感谢。关于这个话题,答案很少。

共有1个答案

浦墨竹
2023-03-14

索引中有一个问题。js

const express = require('express');
const app = express();

require('dotenv').config();

const mysql = require('mysql2');
const connection = mysql.createConnection({
    database: process.env.DB_SCHEMA,
    user: process.env.DB_USER,
    password: process.env.DB_PASS,
    port: process.env.DB_PORT,
    host: process.env.DB_HOST,
});

app.use(express.static('public'));
app.use(express.json());
app.set('view engine', 'ejs');

app.get("/", (req, res) => {
    res.render('index');
});


// get topics
// SELECT *  topic ORDER by topic
app.get("/topics", (req,res) => {
    let topics = [];
    connection.query('SELECT *  FROM topic ORDER by topic', (err,results)=>{
        for(let i = 0; i < results.length; i++){
            topics.push(results[i].topic)
        }
        res.render('topic', {
            topics: topics
        });
    });
});

// get categories
// SELECT *  category;
app.get("/topics/:category", (req,res) => {
    let categories = [];
    connection.query('SELECT * FROM category WHERE category.cat_id = (SELECT cat_id FROM topic WHERE  topic.topic = ?)', [req.params.category], (err,results)=>{
        console.log(req.params.category)
        let categories = []
        for(let i = 0; i < results.length; i++){
            categories.push(results[i].category)
        }
        res.render('category', {
            categories: categories,
            topic: req.params.category
        });
    });
});

// get cards
app.get("/topics/:category/:card", (req,res) => {
    let cards = [];
    connection.query('SELECT * FROM card WHERE card.cat_id = (SELECT cat_id FROM category WHERE  category.category = ?)', [req.params.card], (err,results)=>{
        console.log(req.params.card);
        let cards = [];
        for(let i = 0; i < results.length; i++){
            cards.push(results[i])
        }
        console.log(cards);
        res.render('wordmatch', {
            cards: cards,
            category: req.params.category
        });
    });
});

// create a topic
app.post('/topic', (req, res) => {
    console.log("save topic");
    console.log(req.body);
    let id = req.body.id;
    let topic = req.body.topic;
    console.log("id: "+id);
    console.log("topic: "+topic);
    connection.query('INSERT INTO `topic` (`cat_id`,`topic`) VALUES (?,?)', [id, topic], (err, results) => {
        res.redirect('/');
    });
});

// create a category
// EX: INSERT INTO `category` (`cat_id`, `category`) VALUES ('1', 'stoicisim');
app.post('/category', (req, res) => {
    console.log("save category");
    console.log(req.body);
    let id = req.body.id;
    let category = req.body.category;
    console.log("id: "+id);
    console.log("category: "+category);
    connection.query('INSERT INTO `category` (`cat_id`, `category`) VALUES (?, ?)', [id, category], (err, results) => {
        res.redirect('/');
    });
});

// create a card
/* EX: INSERT INTO `card` (`cat_id`, `prompt`, `question`, `answer`) VALUES ('1', 'prompt', 'question','answer');
*/
app.post('/card', (req, res) => {
    console.log("save card");
    console.log(req.body);
    let id = req.body.id;
    let prompt = req.body.prompt;
    let question = req.body.question;
    let answer = req.body.answer;
    console.log("id: "+id);
    console.log("prompt: "+prompt);
    console.log("question: "+question);
    console.log("answer: "+answer);
    connection.query('INSERT INTO `card` (`cat_id`, `prompt`, `question`, `answer`) VALUES (?, ?, ?, ?);', [id, prompt, question, answer], (err, results) => {
        res.redirect('/');
    });
});

app.listen(process.env.PORT || 3000);

排队

app.use(express.json());

不得不更换

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

现在输出是

save topic
{ request: { body: { id: '8', topic: 'topic ' } } }
id: undefined
topic: undefined
save category
{ id: '8', category: 'CATEGORY' }
id: 8
category: CATEGORY
save card
{ id: '8' }
id: 8
prompt: undefined
question: undefined
answer: undefined

谢啦!

 类似资料:
  • 我在运行程序时遇到此错误 错误: ReferenceError:未在C:\Users\H00422000\desktop\newsletter signup\app中定义选项。第三层的js:39:33。在路由的下一个(C:\Users\H00422000\desktop\newsletter signup\node\u modules\express\lib\router\layer.js:95:

  • 问题内容: 当我在Node服务器上打印请求的内容时,在任何地方都看不到用户数据。 这是我的节点服务器: 这是Angular2代码: 任何人都可以帮我或解释如何处理角度的http请求。 问题答案: 那是你的服务器: 那是您的有角度的客户: 回购https://github.com/kuncevic/angular-httpclient- examples

  • 我正在做一个项目,我需要发送一个音频流到一个节点。js服务器。我可以使用此功能捕获麦克风声音: 如你所见,我能够捕捉音频并在网站上播放。 现在我想把那个音频流发送到一个节点。js服务器,并将其发送回其他客户端。像语音聊天,但我不想使用WebRTC,因为我需要服务器中的流。我怎样才能做到这一点?我可以用插座吗。我想这样做?在我看到的示例中,他们录制了音频,并发送了一个文件,但我需要“实时”音频。

  • 问题内容: 我正在创建一个简单的SOAP Web服务。我要确保它在tomcat Web服务上运行。 我试图用JAX-WS来实现这一点(参见代码) 我的问题是:Endpoint.publish是否使用tomcat服务器来托管该服务器,或者它是小型的glassfish服务器? 我应该扩展UnicastRemoveObject还是类似的东西? 理想情况下,它可以打包成.WAR文件并放在目录中即可正常工作

  • 我将intelliJ IDEA与grails项目一起使用,我需要将其发布到我的Artifactory服务器。我尝试使用以下命令行:grails publish-plugin--noscm--repository=mediatorbaserelease 在我同事的PC中,它工作得很好,但在我的PC中,它向我显示了以下输出:

  • 问题内容: 这是我必须发布的json字符串… 如何发布为JSON? 问题答案: 当然,这是一个重复的问题,但这是完整的示例代码,作为一个长例程。只需复制并粘贴。 首先设置JSON … 接下来,正确异步地将命令和json发送到您的服务器… 最后,(A)使用NSURLConnection正确连接,(B)正确解释从服务器返回给您的信息。 希望它可以节省一些键入的时间!