[英]How do I call a invoke an ajax get request from client side, using Node/Express?
I have a file shuffleRoute.js where I define this:我有一个文件 shuffleRoute.js,我在其中定义了这个:
router.get("/shuffle?jokers=false", function (req, res) {
cards['a','b','c'];
let shuffledCards = _.shuffle(cards);
res.status(200).send(shuffledCards);
});
I have an index.js where I define:我有一个 index.js 在其中定义:
app.get("/v1/game", require("./routes/shuffleRoute.js"));
I have a game.html where onload I need to do an ajax request to get the shuffled cards.我有一个 game.html 在那里 onload 我需要做一个 ajax 请求来获取洗牌的卡片。 How do I do that?
我怎么做?
doing this这样做
$.get( "/v1/game", function(res) {
console.log(res);
});
does not work.不起作用。
I am getting this error:我收到此错误:
jquery-2.2.4.min.js:4 GET localhost:8080/v1/game 500 (Internal Server Error) –
I was using morgan to log things in the server which was incorrectly done.我正在使用摩根在服务器中记录错误完成的事情。
However, commenting that out gives me this error.但是,将其注释掉会给我这个错误。
jquery-2.2.4.min.js:4 GET http://localhost:8080/v1/game 404 (Not Found)
May be wrong but i see routes problem here.可能是错误的,但我在这里看到路线问题。
When you define routes for express use app.use
当您为快速使用
app.use
定义路由时
var myRoute = require('PathToYourRouteFile');
app.use("/v1/game", myRoute);
In route file.在路由文件中。 Im asuming you use express router you need to define something like this
我假设你使用快递路由器,你需要定义这样的东西
youRuoterName.get('/', function(req, res, next) { })
This request will be succes when you go to localhost/v1/game
.当您转到
localhost/v1/game
时,此请求将成功。
If you want another one just do如果你想要另一个就做
youRuoterName.get('/shuffle', function(req, res, next) { })
Which will be succes when you go to /v1/game/shuffle
.当您转到
/v1/game/shuffle
时,这将是成功的。
In your example i see only one route /v1/game/shuffle
which clearly not match /v1/game
and im not even sure that rest of code works as expected.在您的示例中,我只看到一条路线
/v1/game/shuffle
显然与/v1/game
不匹配,我什至不确定其余代码是否按预期工作。
So please read docs carefuly http://expressjs.com/en/4x/api.html#router.route and all should work.所以请仔细阅读文档http://expressjs.com/en/4x/api.html#router.route并且一切都应该有效。
Hope this helps.希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.