【问题标题】:jquery client doesn't get node js server responsejquery客户端没有得到节点js服务器响应
【发布时间】:2018-06-15 16:43:28
【问题描述】:

我可以向节点服务器发送请求,但无法得到响应。 问题出在哪里? 请帮帮我!

我在服务器端(节点 js)有这个:

const express = require('express')
var myParser = require("body-parser");

const app = express() 
app.use(myParser.urlencoded({extended : false}));
app.use(myParser.json());

app.listen(3398, () => console.log('ASK app listening on port 3398!'));

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "admin2",
  password: "password",
  database: "ask_test",
  port: 3306
});

app.post('/selectall', (req, res) =>
    con.query("SELECT * FROM "+req.body.table, function (err, result, fields) {
        if (err) throw err;
        console.log("sending: ");
        console.log(result);
        res.send(result);
    })
);

这在客户端:

$("#sendticket_button").click(function(){

    $.post("http://151.1.140.232:3398/selectall",
        {table: "test1"},
        function(data){
            alert('done');
            $("#sendticket_button").html(data);
            }
    );

}); 

如果我点击按钮“sendticket_button”,我会在服务器控制台上获得带有 DB 字段的预期输出

ASK app listening on port 3398!
sending:
[ RowDataPacket { id: 2, nome: 'massi', cognome: 'matt', eta: 32 },
  RowDataPacket { id: 3, nome: 'car', cognome: 'petr', eta: 23 } ]

但我无法在我的客户端上得到任何东西,也不是警报弹出窗口。我什么都试过了。

谢谢

【问题讨论】:

  • 尝试在 res.send(result); 之后添加 .end()。也许流不会完成/关闭。 -> res.send(result).end();
  • 发送前需要将result转成字符串。
  • 是的,它是必需的。谢谢。

标签: jquery mysql node.js


【解决方案1】:

这是一个 CORS 问题。 这添加到服务器端,解决了这个问题:

app.use(function(req,res,next){
    res.header("Access-Control-Allow-Origin","*");
    next();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 2014-02-13
    • 1970-01-01
    • 2020-08-22
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    相关资源
    最近更新 更多