我试图使一个简单的 chrome 扩展人工智能电子邮件垃圾邮件/火腿分类器。
这是一个chrome扩展,当点击时,在屏幕的四分之一显示一个弹出窗口,如下所示
当单击按钮时,它会将消息发送到python flask服务器,以便应用ML模型,然后返回结果(无论是垃圾邮件还是火腿),但我无法通过CORS限制并获得以下消息
这是我无法摆脱的,即使有一个CORS拦截器浏览器扩展。
下面是我代码:
popup.html
<!DOCTYPE html>
<html>
<head>
<title>My Extension Popup</title>
<style>
body {
font-family: Arial, sans-serif;
font-size: 14px;
margin: 0;
padding: 10px;
width: 100vw;
height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
#logo {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
margin-bottom: 10px;
}
#logo img {
width: 300px;
height: 200px;
margin-bottom: 5px;
}
#title {
text-align: center;
}
input[type="text"] {
display: block;
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
margin-bottom: 10px;
font-size: 16px;
}
button {
display: block;
background-color: #4CAF50;
color: white;
padding: 10px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
button:hover {
background-color: #3e8e41;
}
</style>
<script src="popup.js"></script>
</head>
<body>
<div id="logo">
<img src="logo.png">
<h1>Baye's Based Spam or Ham AI Classifier </h1>
<h4>By Alex Besse Donato</h4>
</div>
<div id="title">
<h2>Enter your email content here:</h2>
</div>
<div>
<form id="myForm">
<input type="text" id="myInput">
<button id="myButton">Send Message to get Analyzed</button>
</form>
</div>
</body>
</html>
popup.js
document.addEventListener("DOMContentLoaded", function() {
var myForm = document.getElementById("myForm");
myForm.addEventListener("submit", function(event) {
event.preventDefault();
var input = document.getElementById("myInput").value;
var url = "http://localhost:5000/analyze";
fetch(url, {
method: "POST",
body: JSON.stringify({ input: input }),
headers: {
"Content-Type": "application/json"
}
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => console.error(error));
});
});
webserver.py
from flask import Flask, request, jsonify
from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(app)
@app.route('/analyze', methods=['POST'])
@cross_origin()
def analyze():
input = request.json['input']
# Your code to analyze the input goes here
result = {"this is a test"} # Replace with your analysis result
return jsonify(result)
if __name__ == '__main__':
app.run(debug=True)
你知道为什么我可能会不断得到CORS错误,即使有一个CORS浏览器扩展?
1条答案
按热度按时间qoefvg9y1#
您的错误与CORS策略无关,请参阅服务器端的错误日志:
TypeError:类型集的对象不可JSON序列化
所以你可以
result = {“this is a test”} #替换为分析结果
日期(例如):
result = {“body”:“这是一个测试”} #替换为您的分析
来制作python字典