Guest User

Untitled

a guest
Oct 18th, 2017
357
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. const rqst = require("request")
  2. var express = require('express');
  3. var app = express();
  4. var http = require('http');
  5. const mysql = require('mysql');
  6. app.post('/getStuff', function(request, response) {
  7. var teamId = '';
  8. var matchId = '';
  9. var query;
  10. var body;
  11. const con = mysql.createConnection({
  12. host: 'myhost.net',
  13. user: 'myuser',
  14. password: 'mypw',
  15. database: 'mydatabase',
  16. });
  17.  
  18. request.on('data', function(data) {
  19. global.data = JSON.parse(data);
  20.  
  21. query = "my correct query";
  22.  
  23. con.connect((err) => {
  24. if (err) {
  25. console.log('Error connecting to Db');
  26. return;
  27. }
  28. console.log('Connection was established');
  29. });
  30.  
  31. let myJSON = [{
  32. "auth": false
  33. }]
  34. con.query(query, (err, rows) => {
  35. if (err) throw err;
  36. if (global.data.teamId == rows[0].homeTeam || global.data.teamId == rows[0].awayTeam) {
  37.  
  38. var url = "http://www.myurl.com/" + global.data.matchId + ".json"
  39. // i can see the json file in my browser if i use this url, so it is correct
  40.  
  41. console.log("the url to the json: " + url);
  42. rqst({
  43. url: url,
  44. json: true
  45. }, function (error, response, body) {
  46.  
  47. if (!error && response.statusCode === 200) {
  48. let myJSON = body;
  49. // if i do a console.log(myJSON) here, it prints the correct json
  50. }
  51. })
  52. }
  53. // below prints 'undefined':
  54. console.log("nThe JSON resultset stringified: " + JSON.stringify(myJSON));
  55. response.end(JSON.stringify(myJSON));
  56. con.end();
  57. });
  58. console.log("DB connection ended");
  59. // this above is put inside the buffer stuff
  60. });
  61. // this seems to be happening before the sql stuff above... :S
  62. request.on('end', function() {
  63. // console.log("This was the query: " + query);
  64. response.setHeader("Content-Type", "text/json");
  65. response.setHeader("Access-Control-Allow-Origin", "*");
  66. });
  67. }); app.listen(8083);
Add Comment
Please, Sign In to add comment