How do i get result in box in current window through express node after click on submit button?












3















I am unable to get a response with node and express when i click the submit button. I am fairly new to node and express. Here is what I have tried. Can you tell me what is wrong with my code? Please guide me on how to get instantaneous response in the box on current html or what is other way to get response instead of async function?



<p class="borderBox"></p>









share|improve this question





























    3















    I am unable to get a response with node and express when i click the submit button. I am fairly new to node and express. Here is what I have tried. Can you tell me what is wrong with my code? Please guide me on how to get instantaneous response in the box on current html or what is other way to get response instead of async function?



    <p class="borderBox"></p>









    share|improve this question



























      3












      3








      3








      I am unable to get a response with node and express when i click the submit button. I am fairly new to node and express. Here is what I have tried. Can you tell me what is wrong with my code? Please guide me on how to get instantaneous response in the box on current html or what is other way to get response instead of async function?



      <p class="borderBox"></p>









      share|improve this question
















      I am unable to get a response with node and express when i click the submit button. I am fairly new to node and express. Here is what I have tried. Can you tell me what is wrong with my code? Please guide me on how to get instantaneous response in the box on current html or what is other way to get response instead of async function?



      <p class="borderBox"></p>






      javascript html express






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 27 '18 at 16:01









      DGRFDSGN

      185112




      185112










      asked Nov 13 '18 at 15:57









      Sonia Sonia

      235




      235
























          1 Answer
          1






          active

          oldest

          votes


















          1














          It's hard to say without seeing all of your code. But I think the first issue is that you aren't checking your req.headers kvps defensively enough. Certain headers are not always present in a request, so you'll need to provide for the case where they don't arrive as expected



               if (req['x-forwarded-for']) {
          var ip = req['x-forwarded-for'].split(',')


          or



               req['x-forwarded-for'] = req['x-forwarded-for'] || ''


          UPDATE



          Judging by what code you have provided, first make the following changes to your server.js code:



          app.get('/headers', function(req, res) {
          if (req.headers['x-forwarded-for'])
          var ip = req.headers["x-forwarded-for"].split(',')[0];
          if (req.headers['accept-language'])
          var lang = req.headers['accept-language'].split(',')
          if (req.headers['user-agent'])
          var sys = req.headers['user-agent'].match(/((.+?))/)[1]


          var obj = {
          "IP Address": ip,
          "Language" : lang,
          "Operating System": sys
          }

          // res.json(obj);
          res.set('Content-Type', 'application/json');
          res.status(200).send(obj);
          });


          Then, you have to make a change to the URI you call with fetch() so it reaches the endpoint you've specified above in your app.get() (i.e. '/headers'). I'm using localhost on port 3000.



          $("#submit").submit(async function(event) {
          event.preventDefault();
          // const response = await fetch(window.location.href);
          const response = await fetch('http://localhost:3000/headers');
          const data = await response.json();
          document.getElementsByClassName('borderBox')[0].innerText = JSON.stringify(data);
          });


          Finally, I don't know much about your project setup, but here's how I did it by serving an index.html file from express using



          app.use(express.static(path.join(__dirname, 'public')));


          and placing index.html in a directory named /public at the root directory of the express app. The file index.html is below:



          <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>

          <p>
          Please click to get the IP address, language, and operating system for your
          device.
          </p>

          <form id="submit">
          <button type="submit">Submit</button>
          </form>


          <p class="borderBox"> </p>

          <script>
          $("#submit").submit(async function(event) {
          event.preventDefault();
          // const response = await fetch(window.location.href);
          const response = await fetch('http://localhost:3000/headers');
          const data = await response.json();
          document.getElementsByClassName('borderBox')[0].innerText = JSON.stringify(data);
          });
          </script>


          I'm just including this last part because, again, I can't see how you've set up your project - but this worked for me.






          share|improve this answer


























          • I edited it at your suggestion but the result still does not come in the box.

            – Sonia
            Nov 14 '18 at 0:39











          • Like I said, without seeing all of the code, it's hard to say. For instance, you use a jquery submit event trigger but you have no form elements on the page. That won't work. Try $("#submit").on('click', => (ev) { ... })

            – elight
            Nov 14 '18 at 4:21











          • Thank for replying. It says that $("#submit").on('click', => (ev) { ... }) throws parsing error. Can you resend correct code statement?

            – Sonia
            Nov 14 '18 at 14:47











          • I edited it to form element on the page, but it still does not work.

            – Sonia
            Nov 14 '18 at 14:59






          • 1





            perhaps you can host this somewhere so people can help debug your issue, like @elight said, without code there isnt a whole lot we can do to help..

            – DGRFDSGN
            Nov 27 '18 at 15:20











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53284821%2fhow-do-i-get-result-in-box-in-current-window-through-express-node-after-click-on%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          It's hard to say without seeing all of your code. But I think the first issue is that you aren't checking your req.headers kvps defensively enough. Certain headers are not always present in a request, so you'll need to provide for the case where they don't arrive as expected



               if (req['x-forwarded-for']) {
          var ip = req['x-forwarded-for'].split(',')


          or



               req['x-forwarded-for'] = req['x-forwarded-for'] || ''


          UPDATE



          Judging by what code you have provided, first make the following changes to your server.js code:



          app.get('/headers', function(req, res) {
          if (req.headers['x-forwarded-for'])
          var ip = req.headers["x-forwarded-for"].split(',')[0];
          if (req.headers['accept-language'])
          var lang = req.headers['accept-language'].split(',')
          if (req.headers['user-agent'])
          var sys = req.headers['user-agent'].match(/((.+?))/)[1]


          var obj = {
          "IP Address": ip,
          "Language" : lang,
          "Operating System": sys
          }

          // res.json(obj);
          res.set('Content-Type', 'application/json');
          res.status(200).send(obj);
          });


          Then, you have to make a change to the URI you call with fetch() so it reaches the endpoint you've specified above in your app.get() (i.e. '/headers'). I'm using localhost on port 3000.



          $("#submit").submit(async function(event) {
          event.preventDefault();
          // const response = await fetch(window.location.href);
          const response = await fetch('http://localhost:3000/headers');
          const data = await response.json();
          document.getElementsByClassName('borderBox')[0].innerText = JSON.stringify(data);
          });


          Finally, I don't know much about your project setup, but here's how I did it by serving an index.html file from express using



          app.use(express.static(path.join(__dirname, 'public')));


          and placing index.html in a directory named /public at the root directory of the express app. The file index.html is below:



          <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>

          <p>
          Please click to get the IP address, language, and operating system for your
          device.
          </p>

          <form id="submit">
          <button type="submit">Submit</button>
          </form>


          <p class="borderBox"> </p>

          <script>
          $("#submit").submit(async function(event) {
          event.preventDefault();
          // const response = await fetch(window.location.href);
          const response = await fetch('http://localhost:3000/headers');
          const data = await response.json();
          document.getElementsByClassName('borderBox')[0].innerText = JSON.stringify(data);
          });
          </script>


          I'm just including this last part because, again, I can't see how you've set up your project - but this worked for me.






          share|improve this answer


























          • I edited it at your suggestion but the result still does not come in the box.

            – Sonia
            Nov 14 '18 at 0:39











          • Like I said, without seeing all of the code, it's hard to say. For instance, you use a jquery submit event trigger but you have no form elements on the page. That won't work. Try $("#submit").on('click', => (ev) { ... })

            – elight
            Nov 14 '18 at 4:21











          • Thank for replying. It says that $("#submit").on('click', => (ev) { ... }) throws parsing error. Can you resend correct code statement?

            – Sonia
            Nov 14 '18 at 14:47











          • I edited it to form element on the page, but it still does not work.

            – Sonia
            Nov 14 '18 at 14:59






          • 1





            perhaps you can host this somewhere so people can help debug your issue, like @elight said, without code there isnt a whole lot we can do to help..

            – DGRFDSGN
            Nov 27 '18 at 15:20
















          1














          It's hard to say without seeing all of your code. But I think the first issue is that you aren't checking your req.headers kvps defensively enough. Certain headers are not always present in a request, so you'll need to provide for the case where they don't arrive as expected



               if (req['x-forwarded-for']) {
          var ip = req['x-forwarded-for'].split(',')


          or



               req['x-forwarded-for'] = req['x-forwarded-for'] || ''


          UPDATE



          Judging by what code you have provided, first make the following changes to your server.js code:



          app.get('/headers', function(req, res) {
          if (req.headers['x-forwarded-for'])
          var ip = req.headers["x-forwarded-for"].split(',')[0];
          if (req.headers['accept-language'])
          var lang = req.headers['accept-language'].split(',')
          if (req.headers['user-agent'])
          var sys = req.headers['user-agent'].match(/((.+?))/)[1]


          var obj = {
          "IP Address": ip,
          "Language" : lang,
          "Operating System": sys
          }

          // res.json(obj);
          res.set('Content-Type', 'application/json');
          res.status(200).send(obj);
          });


          Then, you have to make a change to the URI you call with fetch() so it reaches the endpoint you've specified above in your app.get() (i.e. '/headers'). I'm using localhost on port 3000.



          $("#submit").submit(async function(event) {
          event.preventDefault();
          // const response = await fetch(window.location.href);
          const response = await fetch('http://localhost:3000/headers');
          const data = await response.json();
          document.getElementsByClassName('borderBox')[0].innerText = JSON.stringify(data);
          });


          Finally, I don't know much about your project setup, but here's how I did it by serving an index.html file from express using



          app.use(express.static(path.join(__dirname, 'public')));


          and placing index.html in a directory named /public at the root directory of the express app. The file index.html is below:



          <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>

          <p>
          Please click to get the IP address, language, and operating system for your
          device.
          </p>

          <form id="submit">
          <button type="submit">Submit</button>
          </form>


          <p class="borderBox"> </p>

          <script>
          $("#submit").submit(async function(event) {
          event.preventDefault();
          // const response = await fetch(window.location.href);
          const response = await fetch('http://localhost:3000/headers');
          const data = await response.json();
          document.getElementsByClassName('borderBox')[0].innerText = JSON.stringify(data);
          });
          </script>


          I'm just including this last part because, again, I can't see how you've set up your project - but this worked for me.






          share|improve this answer


























          • I edited it at your suggestion but the result still does not come in the box.

            – Sonia
            Nov 14 '18 at 0:39











          • Like I said, without seeing all of the code, it's hard to say. For instance, you use a jquery submit event trigger but you have no form elements on the page. That won't work. Try $("#submit").on('click', => (ev) { ... })

            – elight
            Nov 14 '18 at 4:21











          • Thank for replying. It says that $("#submit").on('click', => (ev) { ... }) throws parsing error. Can you resend correct code statement?

            – Sonia
            Nov 14 '18 at 14:47











          • I edited it to form element on the page, but it still does not work.

            – Sonia
            Nov 14 '18 at 14:59






          • 1





            perhaps you can host this somewhere so people can help debug your issue, like @elight said, without code there isnt a whole lot we can do to help..

            – DGRFDSGN
            Nov 27 '18 at 15:20














          1












          1








          1







          It's hard to say without seeing all of your code. But I think the first issue is that you aren't checking your req.headers kvps defensively enough. Certain headers are not always present in a request, so you'll need to provide for the case where they don't arrive as expected



               if (req['x-forwarded-for']) {
          var ip = req['x-forwarded-for'].split(',')


          or



               req['x-forwarded-for'] = req['x-forwarded-for'] || ''


          UPDATE



          Judging by what code you have provided, first make the following changes to your server.js code:



          app.get('/headers', function(req, res) {
          if (req.headers['x-forwarded-for'])
          var ip = req.headers["x-forwarded-for"].split(',')[0];
          if (req.headers['accept-language'])
          var lang = req.headers['accept-language'].split(',')
          if (req.headers['user-agent'])
          var sys = req.headers['user-agent'].match(/((.+?))/)[1]


          var obj = {
          "IP Address": ip,
          "Language" : lang,
          "Operating System": sys
          }

          // res.json(obj);
          res.set('Content-Type', 'application/json');
          res.status(200).send(obj);
          });


          Then, you have to make a change to the URI you call with fetch() so it reaches the endpoint you've specified above in your app.get() (i.e. '/headers'). I'm using localhost on port 3000.



          $("#submit").submit(async function(event) {
          event.preventDefault();
          // const response = await fetch(window.location.href);
          const response = await fetch('http://localhost:3000/headers');
          const data = await response.json();
          document.getElementsByClassName('borderBox')[0].innerText = JSON.stringify(data);
          });


          Finally, I don't know much about your project setup, but here's how I did it by serving an index.html file from express using



          app.use(express.static(path.join(__dirname, 'public')));


          and placing index.html in a directory named /public at the root directory of the express app. The file index.html is below:



          <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>

          <p>
          Please click to get the IP address, language, and operating system for your
          device.
          </p>

          <form id="submit">
          <button type="submit">Submit</button>
          </form>


          <p class="borderBox"> </p>

          <script>
          $("#submit").submit(async function(event) {
          event.preventDefault();
          // const response = await fetch(window.location.href);
          const response = await fetch('http://localhost:3000/headers');
          const data = await response.json();
          document.getElementsByClassName('borderBox')[0].innerText = JSON.stringify(data);
          });
          </script>


          I'm just including this last part because, again, I can't see how you've set up your project - but this worked for me.






          share|improve this answer















          It's hard to say without seeing all of your code. But I think the first issue is that you aren't checking your req.headers kvps defensively enough. Certain headers are not always present in a request, so you'll need to provide for the case where they don't arrive as expected



               if (req['x-forwarded-for']) {
          var ip = req['x-forwarded-for'].split(',')


          or



               req['x-forwarded-for'] = req['x-forwarded-for'] || ''


          UPDATE



          Judging by what code you have provided, first make the following changes to your server.js code:



          app.get('/headers', function(req, res) {
          if (req.headers['x-forwarded-for'])
          var ip = req.headers["x-forwarded-for"].split(',')[0];
          if (req.headers['accept-language'])
          var lang = req.headers['accept-language'].split(',')
          if (req.headers['user-agent'])
          var sys = req.headers['user-agent'].match(/((.+?))/)[1]


          var obj = {
          "IP Address": ip,
          "Language" : lang,
          "Operating System": sys
          }

          // res.json(obj);
          res.set('Content-Type', 'application/json');
          res.status(200).send(obj);
          });


          Then, you have to make a change to the URI you call with fetch() so it reaches the endpoint you've specified above in your app.get() (i.e. '/headers'). I'm using localhost on port 3000.



          $("#submit").submit(async function(event) {
          event.preventDefault();
          // const response = await fetch(window.location.href);
          const response = await fetch('http://localhost:3000/headers');
          const data = await response.json();
          document.getElementsByClassName('borderBox')[0].innerText = JSON.stringify(data);
          });


          Finally, I don't know much about your project setup, but here's how I did it by serving an index.html file from express using



          app.use(express.static(path.join(__dirname, 'public')));


          and placing index.html in a directory named /public at the root directory of the express app. The file index.html is below:



          <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>

          <p>
          Please click to get the IP address, language, and operating system for your
          device.
          </p>

          <form id="submit">
          <button type="submit">Submit</button>
          </form>


          <p class="borderBox"> </p>

          <script>
          $("#submit").submit(async function(event) {
          event.preventDefault();
          // const response = await fetch(window.location.href);
          const response = await fetch('http://localhost:3000/headers');
          const data = await response.json();
          document.getElementsByClassName('borderBox')[0].innerText = JSON.stringify(data);
          });
          </script>


          I'm just including this last part because, again, I can't see how you've set up your project - but this worked for me.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 14 '18 at 17:45

























          answered Nov 13 '18 at 16:28









          elightelight

          809




          809













          • I edited it at your suggestion but the result still does not come in the box.

            – Sonia
            Nov 14 '18 at 0:39











          • Like I said, without seeing all of the code, it's hard to say. For instance, you use a jquery submit event trigger but you have no form elements on the page. That won't work. Try $("#submit").on('click', => (ev) { ... })

            – elight
            Nov 14 '18 at 4:21











          • Thank for replying. It says that $("#submit").on('click', => (ev) { ... }) throws parsing error. Can you resend correct code statement?

            – Sonia
            Nov 14 '18 at 14:47











          • I edited it to form element on the page, but it still does not work.

            – Sonia
            Nov 14 '18 at 14:59






          • 1





            perhaps you can host this somewhere so people can help debug your issue, like @elight said, without code there isnt a whole lot we can do to help..

            – DGRFDSGN
            Nov 27 '18 at 15:20



















          • I edited it at your suggestion but the result still does not come in the box.

            – Sonia
            Nov 14 '18 at 0:39











          • Like I said, without seeing all of the code, it's hard to say. For instance, you use a jquery submit event trigger but you have no form elements on the page. That won't work. Try $("#submit").on('click', => (ev) { ... })

            – elight
            Nov 14 '18 at 4:21











          • Thank for replying. It says that $("#submit").on('click', => (ev) { ... }) throws parsing error. Can you resend correct code statement?

            – Sonia
            Nov 14 '18 at 14:47











          • I edited it to form element on the page, but it still does not work.

            – Sonia
            Nov 14 '18 at 14:59






          • 1





            perhaps you can host this somewhere so people can help debug your issue, like @elight said, without code there isnt a whole lot we can do to help..

            – DGRFDSGN
            Nov 27 '18 at 15:20

















          I edited it at your suggestion but the result still does not come in the box.

          – Sonia
          Nov 14 '18 at 0:39





          I edited it at your suggestion but the result still does not come in the box.

          – Sonia
          Nov 14 '18 at 0:39













          Like I said, without seeing all of the code, it's hard to say. For instance, you use a jquery submit event trigger but you have no form elements on the page. That won't work. Try $("#submit").on('click', => (ev) { ... })

          – elight
          Nov 14 '18 at 4:21





          Like I said, without seeing all of the code, it's hard to say. For instance, you use a jquery submit event trigger but you have no form elements on the page. That won't work. Try $("#submit").on('click', => (ev) { ... })

          – elight
          Nov 14 '18 at 4:21













          Thank for replying. It says that $("#submit").on('click', => (ev) { ... }) throws parsing error. Can you resend correct code statement?

          – Sonia
          Nov 14 '18 at 14:47





          Thank for replying. It says that $("#submit").on('click', => (ev) { ... }) throws parsing error. Can you resend correct code statement?

          – Sonia
          Nov 14 '18 at 14:47













          I edited it to form element on the page, but it still does not work.

          – Sonia
          Nov 14 '18 at 14:59





          I edited it to form element on the page, but it still does not work.

          – Sonia
          Nov 14 '18 at 14:59




          1




          1





          perhaps you can host this somewhere so people can help debug your issue, like @elight said, without code there isnt a whole lot we can do to help..

          – DGRFDSGN
          Nov 27 '18 at 15:20





          perhaps you can host this somewhere so people can help debug your issue, like @elight said, without code there isnt a whole lot we can do to help..

          – DGRFDSGN
          Nov 27 '18 at 15:20


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53284821%2fhow-do-i-get-result-in-box-in-current-window-through-express-node-after-click-on%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Full-time equivalent

          Bicuculline

          さくらももこ