“My frontend can’t connect to the backend address, but I can make a POST request with curl. Here is the browser error: net::ERR_CONNECTION_REFUSED at (index):9 when trying to POST to http://127.0.0.1:5000/process-data.”
Front-end code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hello</title>
<script>
function sendData() {
// Make sure the URL is the Flask application address, usually http://127.0.0.1:5000/process-data if it's local
fetch('http://127.0.0.1:5000/process-data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({message: 'Hello, backend!'}),
})
.then(response => response.json())
.then(data => {
// Display the data returned from the backend on the webpage
document.getElementById('response').innerText = data.reply;
})
.catch((error) => {
console.error('Error:', error);
});
}
</script>
</head>
<body>
<button onclick="sendData()">Send data to backend</button>
<div id="response">The response from the backend will be displayed here.</div>
</body>
</html>
Back-end code:
from flask import Flask, request, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route('/process-data', methods=['POST'])
def process_data():
# Retrieve the data sent from the front-end
data = request.json
print(data) # Just as an example, the data might need to be processed in a real application
# Suppose this is the response after processing
reply = {'reply': f"Backend received your message: {data.get('message')}"}
# Return the processed result to the front-end
return jsonify(reply)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
This translation includes the comments within the code for clarity.
I’ve been trying to enable interaction between the front end and the back end to create a website.