我正在使用Microsoft.ApsNetCore.Cors 2.2
“通过'exampleapi.local'访问XMLHttpRequest 来自来源“ example.local”的信息已被CORS政策阻止: 请求中没有'Access-Control-Allow-Origin'标头 资源。”
我以此设置设置
=IFERROR(INDEX(Returns!$B:$B,MATCH($A2,Returns!$A:$A,0)),"")
但是它不起作用,总是出现相同的错误
答案 0 :(得分:1)
我刚刚失去了几分钟试图找出为什么CORS没有从工作的请求http://localhost:8080,我根据官方文档已经设置。
好吧,因为我在URL的末尾添加了一个'/'。因此,从允许的来源中删除“ /”。
Microsoft文档上甚至还有关于此的注释!
注意:URL不得包含斜杠(/)。如果网址 以/终止,比较返回false并且没有头 返回。
答案 1 :(得分:1)
简单易行的方法。
from PyQt5 import QtCore, QtGui, QtWidgets
import urllib
import speech_recognition as sr
import threading
import time
import import_ipynb
from gui import Ui_Function
class Ui_welcome(object):
def openfunc(self):
self.window = QtWidgets.QMainWindow()
self.ui = Ui_Function()
self.ui.setupUi(self.window)
welcome.hide()
self.window.show()
def setupUi(self, welcome):
welcome.setObjectName("welcome")
welcome.resize(739, 600)
welcome.setStyleSheet("Background-color: #696969;")
self.centralwidget = QtWidgets.QWidget(welcome)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(70, 90, 601, 61))
self.label.setStyleSheet("\n"
"font-family: Lucida Console;\n"
"font-size: 25px;\n"
"font-weight: bold;\n"
"font-style: italic;\n"
"color: #ffffff;\n"
"")
self.label.setObjectName("label")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(240, 250, 281, 71))
self.pushButton.setStyleSheet("QPushButton{\n"
"color: #ffffff;\n"
"background-color: #ff6347;\n"
"Border-radius: 30px;\n"
"font-size:30px\n"
"}\n"
"QPushButton:hover{\n"
"color: #ffffff;\n"
"background-color: #ff6347;\n"
"Border-radius: 30px;\n"
"background-color: #ff4500;\n"
"font-weight: bold;\n"
"}")
self.pushButton.setObjectName("pushButton")
self.pushButton.clicked.connect(self.openfunc)
welcome.setCentralWidget(self.centralwidget)
self.retranslateUi(welcome)
QtCore.QMetaObject.connectSlotsByName(welcome)
def retranslateUi(self, welcome):
_translate = QtCore.QCoreApplication.translate
welcome.setWindowTitle(_translate("welcome", "MainWindow"))
self.label.setText(_translate("welcome", "Welcome To Book Recommendation System"))
self.pushButton.setText(_translate("welcome", "Let\'s get started"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
welcome = QtWidgets.QMainWindow()
ui = Ui_welcome()
ui.setupUi(welcome)
welcome.show()
app.exec_()
from PyQt5 import QtCore, QtGui, QtWidgets
import urllib
import speech_recognition as sr
import threading
import time
import import_ipynb
from Untitled12 import *
def connected(host="http://google.com"):
try:
urllib.request.urlopen(host)
return True
except:
return False
class Ui_Function(object):
def setupUi(self, Function):
Function.setObjectName("Function")
Function.resize(737, 600)
Function.setStyleSheet("Background-color: #696969;")
self.centralwidget = QtWidgets.QWidget(Function)
self.centralwidget.setObjectName("centralwidget")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(50, 70, 601, 31))
self.lineEdit.setStyleSheet("color: #ffffff")
self.lineEdit.setObjectName("lineEdit")
self.lineEdit.setPlaceholderText("Enter Book Name...")
self.label = QtWidgets.QLabel(self.centralwidget)
#self.label.setGeometry(QtCore.QRect(50, 30, 151, 17))
self.label.setGeometry(QtCore.QRect(50, 40, 191, 17))
self.label.setStyleSheet("QLabel{\n"
"color: #ffffff;\n"
"font-family: Lucida Console;\n"
"font-size: 15px;\n"
"}")
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(320, 120, 67, 17))
self.label_2.setObjectName("label_2")
self.label_2.setStyleSheet("QLabel{\n"
"color: #ffffff;\n"
"font-family: Lucida Console;\n"
"font-size: 20px;\n"
"}")
self.label_3 = QtWidgets.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(50, 150, 311, 21))
self.label_3.setObjectName("label_3")
self.label_3.setStyleSheet("QLabel{\n"
"color: #ffffff;\n"
"font-family: Lucida Console;\n"
"font-size: 15px;\n"
"}")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(50, 180, 121, 41))
self.pushButton.setObjectName("pushButton")
self.pushButton.setStyleSheet("QPushButton{\n"
"color: #ffffff;\n"
"background-color: #ff6347;\n"
"Border-radius: 10px;\n"
"}\n"
"QPushButton:hover{\n"
"color: #ffffff;\n"
"background-color: #ff6347;\n"
"Border-radius: 10px;\n"
"background-color: #ff4500;\n"
"font-weight:bold;\n"
"}")
self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
self.textEdit.setGeometry(QtCore.QRect(60, 320, 601, 231))
self.textEdit.setObjectName("textEdit")
self.textEdit.setStyleSheet("QTextEdit{\n"
"Background-color: #ffffff;\n"
"}")
self.label_4 = QtWidgets.QLabel(self.centralwidget)
self.label_4.setGeometry(QtCore.QRect(60, 290, 141, 21))
self.label_4.setObjectName("label_4")
self.label_4.setStyleSheet("QLabel{\n"
"color: #ffffff;\n"
"font-family: Lucida Console;\n"
"font-size: 15px;\n"
"}")
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(538, 110, 111, 41))
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_2.setStyleSheet("QPushButton{\n"
"color: #ffffff;\n"
"background-color: #ff6347;\n"
"Border-radius: 10px;\n"
"}\n"
"QPushButton:hover{\n"
"color: #ffffff;\n"
"Background-color: #ff6347;\n"
"Border-radius: 10px;\n"
"background-color: #ff4500;\n"
"font-weight: bold;\n"
"}")
#self.pushButton_2.clicked.connect(Untitled12.give_rec("Angel of Hope"))
self.label_5 = QtWidgets.QLabel(self.centralwidget)
self.label_5.setGeometry(QtCore.QRect(60, 220, 241, 21))
self.label_5.setObjectName("label_5")
self.label_5.setStyleSheet("QLabel{\n"
"color: #ffffff;\n"
"font-family: Lucida Console;\n"
"}")
self.comboBox = QtWidgets.QComboBox(self.centralwidget)
self.comboBox.setGeometry(QtCore.QRect(400, 180, 251, 31))
self.comboBox.setStyleSheet("QcomboBox{\n"
"color: #ffffff;\n"
"Background-color: #ffffff;\n"
"font-family: Lucida Console;\n"
"}")
self.comboBox.setObjectName("comboBox")
self.comboBox.addItem("Your Book Name here...")
self.comboBox.currentIndexChanged.connect(self.changeText)
Function.setCentralWidget(self.centralwidget)
self.retranslateUi(Function)
QtCore.QMetaObject.connectSlotsByName(Function)
def changeText(self, index):
self.lineEdit.setText(self.comboBox.itemText(index))
def retranslateUi(self, Function):
_translate = QtCore.QCoreApplication.translate
Function.setWindowTitle(_translate("Function", "MainWindow"))
self.label.setText(_translate("Function", "Enter the Book Name:"))
self.label_2.setText(_translate("Function", "OR"))
self.label_3.setText(
_translate("Function", "Write the Book Name by your Voice:")
)
self.pushButton.setText(_translate("Function", "Click and Say"))
self.label_4.setText(_translate("Function", "Recommendations:"))
self.pushButton_2.setText(_translate("Function", "Search"))
self.label_5.setText(_translate("Function", "Suggestions..."))
class SpeechWorker(QtCore.QObject):
messageChanged = QtCore.pyqtSignal(str)
itemsChanged = QtCore.pyqtSignal(list)
def speech(self):
threading.Thread(target=self._speech, daemon=True).start()
def _speech(self):
if connected():
r = sr.Recognizer()
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source)
self.messageChanged.emit("Listening...")
time.sleep(1)
# read the audio data from the default microphone
try:
audio_data = r.listen(source, timeout=5)
except sr.WaitTimeoutError as e:
print("Timeout; {0}".format(e))
self.messageChanged.emit("Time over")
time.sleep(1)
self.messageChanged.emit("Recognizing...")
time.sleep(1)
# convert speech to text
text = r.recognize_google(audio_data, language="en-UK", show_all=True)
try:
self.messageChanged.emit("You said:")
self.itemsChanged.emit([])
list1 = []
if len(text) > 0:
print(len(text["alternative"]))
for x in range(0, len(text["alternative"])):
list1.append(text["alternative"][x]["transcript"])
self.itemsChanged.emit(list1)
else:
time.sleep(1)
self.messageChanged.emit("\tNothing")
except LookupError:
time.sleep(1)
self.messageChanged.emit("Could not Understand Value")
except sr.UnknownValueError:
time.sleep(1)
self.messageChanged.emit(
"Voice Recognition could not understand audio"
)
except sr.RequestError as e:
time.sleep(1)
self.messageChanged.emit(
"Voice Recognition could not request results ; {0}".format(e)
)
else:
time.sleep(1)
self.messageChanged.emit(
"NO Internet Connection. \nCheck your Internet Connection"
)
time.sleep(1)
self.messageChanged.emit("Completed")
time.sleep(2)
self.messageChanged.emit("Suggestions...")
class Function(QtWidgets.QMainWindow, Ui_Function):
def __init__(self, parent=None):
super(Function, self).__init__(parent)
self.setupUi(self)
self.worker = SpeechWorker()
self.worker.messageChanged.connect(self.updateMessage)
self.worker.itemsChanged.connect(self.updateItems)
self.pushButton.clicked.connect(self.worker.speech)
self.pushButton_2.clicked.connect(self.updateEditBox)
@QtCore.pyqtSlot(str)
def updateMessage(self, message):
self.label_5.setText(message)
self.label_5.adjustSize()
@QtCore.pyqtSlot(list)
def updateItems(self, items):
self.comboBox.clear()
self.comboBox.addItems(items)
@QtCore.pyqtSlot()
def updateEditBox(self):
print(self.lineEdit.text())
string=give_rec(self.lineEdit.text())
self.textEdit.clear()
self.textEdit.setText("\tRecommendations of "+self.lineEdit.text().title()+"\t")
i=1
for names in string:
self.textEdit.append(str(i)+" - "+str(names))
i=i+1
self.comboBox.clear()
self.lineEdit.setText("")
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = Function()
w.show()
app.exec_()
答案 2 :(得分:0)
这是这里提供的示例:ASP.NET Core 2.2
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder => builder.WithOrigins("http://example.com"));
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Shows UseCors with named policy.
app.UseCors("AllowSpecificOrigin");
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
最终在控制器或动作上像这样使用它:
[EnableCors("AllowSpecificOrigin")]
还出于某种原因,请确保在app.UseMVC之前先调用app.UseCors。
如果您需要的只是来自单一来源的CORS,您可以使用没有政策的简单解决方案:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors(
options => options.WithOrigins("http://example.com").AllowAnyMethod()
);
app.UseMvc();
}
答案 3 :(得分:0)
艾米的评论正确。 CORS标头需要由目标服务器而不是您的目标服务器来设置。
如果您尝试连接到其他端口上的API,但在同一IP地址上本地运行,则会经常遇到CORS问题(最常见的示例是localhost:<>尝试ping localhost <>,等等。 )。
如果您尝试使用Google chrome在本地计算机上运行此程序,则可以下载以下扩展程序,该扩展程序可用于启用和禁用CORS规则,以便您可以在本地进行测试: Allow CORS: Access-Control-Allow-Origin
答案 4 :(得分:0)
我知道这是一个老问题,但是如果像我一样,您正在使用appsettings.json文件进行配置,请确保添加以下内容:
"cors": {
"rules": [
{
"origin": "https://localhost:44379",
"allow": true
}
]}
这种简单的添加使一切神奇地为我工作。