Cannot access localhost:8080 from browser

Viewed 3337

I am running this simple command in my terminal:

python -m http.server 8080

But when I try to access localhost:8080, nothing came out. Why does this happen? Can someone help me?

Thanks in advance.

When I tried another python code provided by the Udacity course:

#!/usr/bin/env python3
# 
# A buggy web service in need of a database.

from flask import Flask, request, redirect, url_for

from forumdb import get_posts, add_post

app = Flask(__name__)

# HTML template for the forum page
HTML_WRAP = '''\
<!DOCTYPE html>
<html>
  <head>
    <title>DB Forum</title>
    <style>
      h1, form { text-align: center; }
      textarea { width: 400px; height: 100px; }
      div.post { border: 1px solid #999;
                 padding: 10px 10px;
                 margin: 10px 20%%; }
      hr.postbound { width: 50%%; }
      em.date { color: #999 }
    </style>
  </head>
  <body>
    <h1>DB Forum</h1>
    <form method=post>
      <div><textarea id="content" name="content"></textarea></div>
      <div><button id="go" type="submit">Post message</button></div>
    </form>
    <!-- post content will go here -->
%s
  </body>
</html>
'''

# HTML template for an individual comment
POST = '''\
    <div class=post><em class=date>%s</em><br>%s</div>
'''


@app.route('/', methods=['GET'])
def main():
  '''Main page of the forum.'''
  posts = "".join(POST % (date, text) for text, date in get_posts())
  html = HTML_WRAP % posts
  return html


@app.route('/', methods=['POST'])
def post():
  '''New post submission.'''
  message = request.form['content']
  add_post(message)
  return redirect(url_for('main'))


if __name__ == '__main__':
  app.run(host='0.0.0.0', port=8000)

when I tried this for the first time, it worked just fine. But then I closed the terminal. The second time I try to run this python file, I couldn't connect to localhost:8000 anymore.

the same problem keeps coming back. Sometimes it works fine and I see the page I want. Why is that?

Question: Do I run the webserver from my virtualMachine or from my macos system?

2 Answers

Firstly, create a python file (server.py) in your project file.

Copy the code below into server.py

import http.server
import socketserver

PORT  = 8080

Handler = http.server.SimpleHTTPRequestHandler
httpd = socketserver.TCPServer(("",PORT), Handler)
print("Server at PORT : ",PORT)
httpd.serve_forever()

After that, run the following code command=>

python server.py

Maybe nothing comes out because it's an empty server? You have no HTML content.

You can do this

mkdir /tmp/www
echo 'It works' > /tmp/www/index.html
python -m http.server 8080 --directory /tmp/www

And in a new terminal

curl -v http://localhost:8080

You should see something

Related