【发布时间】:2018-08-12 02:32:36
【问题描述】:
做第二个 CS50 项目,我要做的第一件事是创建一个 index.html 页面,我必须在其中输入用户名并显示它。我必须使用 SocketIO 来让其他用户也能看到它。
当我运行我的 Flask 应用程序并转到页面时,我在控制台中收到以下文本:
flask run
* Serving Flask-SocketIO app "main.py"
* Forcing debug mode on
* Restarting with stat
* Debugger is active!
* Debugger PIN: 399-480-796
127.0.0.1 - - [2018-08-12 05:17:54] "GET / HTTP/1.1" 200 1123 0.008075
127.0.0.1 - - [2018-08-12 05:17:55] "GET /index.js HTTP/1.1" 404 342 0.000796
127.0.0.1 - - [2018-08-12 05:17:55] "GET /static/index.js HTTP/1.1" 404 342 0.000821
127.0.0.1 - - [2018-08-12 05:17:55] "GET /static/index.js HTTP/1.1" 404 342 0.003149
但是当我按下“Enter”按钮时,它会因“不允许的方法”而失败,而我在控制台中看到的是:
127.0.0.1 - - [2018-08-12 05:18:01] "POST / HTTP/1.1" 405 323 0.003737
project_folder/main.py:
from flask import Flask, jsonify, render_template, request
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.config["SECRET_KEY"] = 'dev'
socketio = SocketIO(app)
@app.route("/")
def index():
return render_template("index.html")
@socketio.on("new user")
def new(data):
username = data["username"]
emit('plus user', {'username': username}, broadcast=True)
project_folder/templates/layout.html:
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
<script type='text/javascript' src='index.js'></script>
<script src='{{ url_for('static', filename='index.js') }}'></script>
</head>
<body>
<div class="container">
{% block body %}
{% endblock %}
</div>
</body>
</html>
project_folder/templates/index.html:
{% extends "layout.html" %}
{% block title %}
Sign In
{% endblock %}
{% block body %}
<form action="{{ url_for('index') }}" method='post'>
<h1>Hi! In this chat room you can be whoever you want.</h1>
<h2>The only thing I ask you is to tell me the name I'll be calling you.</h2>
<h3>You don't have to tell me your real name.</h3>
<h4>Enjoy.</h4>
<br>
<div class="form-group">
<input class="form-control" name='username' autofocus placeholder="Username">
</div>
<div class="formgroup">
<button id='newuser' class='btn btn-primary' data-new='username'>Enter</button>
</div>
<ul id="users"></ul>
</form>
{% endblock %}
project_folder/templates/index.js:
document.addEventListener('DOMContentLoaded', () => {
// connect to websocket
var socket = io.connect(location.protocol + '//' + document.domain + ":" + location.port);
// when connected, configure buttons
socket.on('connect', () => {
document.querySelector('#newuser').onclick = () => {
const username = newuser.dataset.new;
socket.emit('new user', {'username': username})
};
});
});
// When a new user has registered , add to the ul
socket.on('plus user', data => {
const li = document.createElement('li');
li.innerHTML = data.username;
document.querySelector('#users').append(li);
});
这几乎是相同的任务,我从讲座视频中提取了大约 90% 的代码,但并没有错。我做错了什么?
【问题讨论】: