angular - CORS 配置 Flask、Angular 和 NGINX
问题描述
我正在尝试使用 nginx 将 Angular 应用程序上传到数字海洋水滴。这个应用程序使用烧瓶中的 API。在本地一切正常,但在 VPS 上无法正常工作。它说了一些关于Cross-origin request blocked: Same origin policy does not allow reading of remote resources at http://127.0.0.1:5001/api/talk/
这是我的 nginx 配置:
server {
server_name x.domain.com;
location / {
proxy_pass http://127.0.0.1:4200;
proxy_set_header Host x.domain.com;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Protocol $scheme;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Origin "";
add_header "Access-Control-Allow-Origin" "*";
add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
}
}
server {
location / {
proxy_pass http://127.0.0.1:5001;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Protocol $scheme;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Origin "";
add_header "Access-Control-Allow-Origin" "*";
add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
}
location /api/talk/ {
proxy_pass http://127.0.0.1:5001;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Protocol $scheme;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Origin "";
}
location /api/response/ {
proxy_pass http://127.0.0.1:5001;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Protocol $scheme;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Origin "";
}
}
这是我的烧瓶配置:
app = Flask(__name__)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
chat = Chat()
@app.route('/api/talk/', methods=['POST'])
@cross_origin(origin='localhost')
def index():
print(request.data.decode("utf-8"))
chat.send_message(request.data)
return request.data
@app.route('/api/response/', methods=['GET'])
@cross_origin(origin='localhost')
def get():
response = chat.response
return response
def options(self):
return {'Allow': 'POST'}, 200, \
{'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST,GET'}
if __name__ == '__main__':
app.run(host='127.0.0.1', port=5001, debug=True)
并且 Angular 在这里使用烧瓶 API:
export class Message {
constructor(public content: string, public sentBy: string){ }
}
@Injectable({
providedIn: "root",
})
export class MessageService {
conversation = new BehaviorSubject<Message[]>([]);
readonly SERVER_URL = "http://127.0.0.1:5001";
public httpClient = axios.create();
constructor(){}
update(msg: Message) {
this.conversation.next([msg]);
}
converse(msg: string) {
const userMessage = new Message(msg, 'user');
this.update(userMessage);
this.sendMessage(userMessage.content)
}
sendMessage(msg: string) {
console.log(msg)
const config = {
headers: {
'Content-Type': 'text/plain',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Methods': 'GET POST',
'Access-Control-Allow-Origin': '*'
},
};
this.httpClient.post(this.SERVER_URL+'/api/talk/', btoa(msg), config)
.then(function (response) {
})
.catch(function (error) {
console.log(error);
});
}
async getResponse() {
await this.delay(900);
let msg = ''
return this.httpClient.get(this.SERVER_URL+'/api/response/')
.then(response => {
msg = response.data
const botMessage = new Message(msg, 'chucho');
this.update(botMessage);
return msg
})
.catch(function (error) {
console.log(error);
});
}
delay(ms: number) {
return new Promise( resolve => setTimeout(resolve, ms) );
}
}
我的 Angular 应用程序在 4200 端口上运行,而 Flask API 在 5001 端口上。
希望您能够帮助我。
解决方案
尝试像这样启用 CORS -
但首先通过运行安装最新的烧瓶 -
pip install -U flask-cors
from flask import Flask
from flask_cors import CORS, cross_origin
app = Flask(__name__)
cors = CORS(app) # This will enable CORS for all routes
@app.route("/")
@cross_origin()
def helloWorld():
return "Helloworld!"
推荐阅读
- c++ - 为什么我将垃圾值作为输出?
- reactjs - 组件上的不同全局状态反应 redux
- javascript - 下拉问题清除选择
- ios - react-native-permission 消息与 ios 中的 info.plist 文件中写入的消息不同
- javascript - 根据多个属性从对象数组中过滤重复项,包括原始值
- javascript - 如何将数据从子级传递给父级并根据下拉列表中的选定值呈现内容?
- sql - 如何在 SQL 中的特定字符之前或之后提取文本
- c - 在c中实现字符串到int函数
- salesforce - Salesforce:通过用户添加的 Content Key 获取图像,使用代码元数据中的 ContentReference
- flutter - 每当键盘出现颤动时,文本字段就会缩小