XMLHttpRequest无法加载url。请求标头字段预检响应中的Access-Control-Allow-Headers不允许授权

时间:2017-03-15 14:50:22

标签: jquery ajax .htaccess cors slim

我决定将我的html5游戏上传到Facebook平台,但我对我的api /服务器的请求有问题,因为现在请求来自不同的域(Environment: Request Method: GET Request URL: //localhost:3000/articles/test-title/ Django Version: 1.10.4 Python Version: 2.7.13 Installed Applications: ('collectfast', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.redirects', 'taggit', 'modelcluster', 'storages', 'wagtail.wagtailcore', 'wagtail.wagtaildocs', 'wagtail.wagtailsnippets', 'wagtail.wagtailusers', 'wagtail.wagtailimages', 'wagtail.wagtailembeds', 'wagtail.wagtailsearch', 'wagtail.wagtailredirects', 'wagtail.wagtailforms', 'wagtail.wagtailsites', 'wagtail.contrib.wagtailsitemaps', 'btcmag', 'user_sessions', 'wagtail.wagtailadmin', 'wagtail.contrib.modeladmin', 'wagtail.contrib.wagtailfrontendcache', 'admin_honeypot', 'django_otp', 'django_otp.plugins.otp_static', 'django_otp.plugins.otp_totp', 'otp_yubikey', 'two_factor', 'cachalot', 'wagtail.contrib.wagtailstyleguide') Installed Middleware: ('django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'user_sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django_otp.middleware.OTPMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'wagtail.wagtailcore.middleware.SiteMiddleware', 'wagtail.wagtailredirects.middleware.RedirectMiddleware', 'django.contrib.redirects.middleware.RedirectFallbackMiddleware', 'genesis.settings.custom.UserBasedExceptionMiddleware') Template error: In template C:\BTC\btcmag\btcmag\templates\blocks\featured_left_aligned_image.html, error at line 2 Unable to locate credentials 1 : {% load wagtailimages_tags %} 2 : {% image self.image original as page_image %} 3 : 4 : <div class="container py-4"> 5 : <div class="col-12 mx-auto"> 6 : <div class="featured-content row"> 7 : <div class="col"> 8 : <div class="featured-highlight-module" 9 : style="background-image: url({{ page_image.url }})"> 10 : </div> 11 : </div> 12 : <div class="col"> Traceback: File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\django\core\handlers\base.py" in _get_response 215. response = response.render() File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\django\template\response.py" in render 109. self.content = self.rendered_content File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\django\template\response.py" in rendered_content 86. content = template.render(context, self._request) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\django\template\backends\jinja2.py" in render 71. return self.template.render(context) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\jinja2\environment.py" in render 989. return self.environment.handle_exception(exc_info, True) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\jinja2\environment.py" in handle_exception 754. reraise(exc_type, exc_value, tb) File "C:\BTC\btcmag\btcmag\jinja2\btcmag\pages\featured.html" in top-level template code 1. {% extends "btcmag/base.html" %} File "C:\BTC\btcmag\btcmag\jinja2\btcmag\base.html" in top-level template code 190. {% block body %}{% endblock body %} File "C:\BTC\btcmag\btcmag\jinja2\btcmag\pages\featured.html" in block "body" 51. {{ page.body }} File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\markupsafe\_native.py" in escape 21. return s.__html__() File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\wagtail\wagtailcore\blocks\stream_block.py" in __html__ 358. return self.stream_block.render(self) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\wagtail\wagtailcore\blocks\base.py" in render 232. return self.render_basic(value, context=context) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\wagtail\wagtailcore\blocks\stream_block.py" in render_basic 219. for child in value File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\wagtail\wagtailcore\blocks\base.py" in render 418. return self.block.render(self.value, context=context) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\wagtail\wagtailcore\blocks\base.py" in render 240. return mark_safe(render_to_string(template, new_context)) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\django\template\loader.py" in render_to_string 68. return template.render(context, request) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\django\template\backends\django.py" in render 66. return self.template.render(context) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\django\template\base.py" in render 208. return self._render(context) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\django\template\base.py" in _render 199. return self.nodelist.render(context) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\django\template\base.py" in render 994. bit = node.render_annotated(context) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\django\template\base.py" in render_annotated 961. return self.render(context) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\wagtail\wagtailimages\templatetags\wagtailimages_tags.py" in render 88. rendition = get_rendition_or_not_found(image, self.filter) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\wagtail\wagtailimages\shortcuts.py" in get_rendition_or_not_found 16. return image.get_rendition(specs) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\wagtail\wagtailimages\models.py" in get_rendition 284. generated_image = filter.run(self, BytesIO()) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\wagtail\wagtailimages\models.py" in run 397. with image.get_willow_image() as willow: File "c:\python27\Lib\contextlib.py" in __enter__ 17. return self.gen.next() File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\wagtail\wagtailimages\models.py" in get_willow_image 180. image_file = storage.open(self.file.name, 'rb') File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\django\core\files\storage.py" in open 38. return self._open(name, mode) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\storages\backends\s3boto3.py" in _open 424. f = self.file_class(name, mode, self) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\storages\backends\s3boto3.py" in __init__ 98. self.obj.load() File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\boto3\resources\factory.py" in do_action 505. response = action(self, *args, **kwargs) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\boto3\resources\action.py" in __call__ 83. response = getattr(parent.meta.client, operation_name)(**params) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\botocore\client.py" in _api_call 251. return self._make_api_call(operation_name, kwargs) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\botocore\client.py" in _make_api_call 526. operation_model, request_dict) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\botocore\endpoint.py" in make_request 141. return self._send_request(request_dict, operation_model) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\botocore\endpoint.py" in _send_request 166. request = self.create_request(request_dict, operation_model) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\botocore\endpoint.py" in create_request 150. operation_name=operation_model.name) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\botocore\hooks.py" in emit 227. return self._emit(event_name, kwargs) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\botocore\hooks.py" in _emit 210. response = handler(**kwargs) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\botocore\signers.py" in handler 90. return self.sign(operation_name, request) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\botocore\signers.py" in sign 147. auth.add_auth(request) File "C:\Users\Pablo\Envs\btcmag\lib\site-packages\botocore\auth.py" in add_auth 665. raise NoCredentialsError Exception Type: NoCredentialsError at /articles/test-title/ Exception Value: Unable to locate credentials )。

我收到了这个错误:

XMLHttpRequest无法加载https://myurl/api/login。请求标题字段预检响应中的Access-Control-Allow-Headers不允许授权。

这是我的AJAX请求:

<Window x:Class="FileHelperTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="2*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <TabControl ItemsSource="{Binding AllServers}" SelectedItem="{Binding SelectedServer, Mode=TwoWay}">
        <TabControl.ItemTemplate>
            <!-- this is the header template-->
            <DataTemplate>
                <Grid>
                <TextBlock Text="{Binding Name}"/>
                <Button HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
                    Content="{Binding Name}"
                    Command="{Binding DataContext.AddNew, RelativeSource={RelativeSource AncestorType=TabControl}, Mode=OneTime}" 
                    CommandParameter="{Binding}" >
                    <Button.Style>
                        <Style TargetType="{x:Type  Button}">
                            <Setter Property="Visibility" Value="Collapsed"/>
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding Name}" Value="+" >
                                    <Setter Property="Visibility" Value="Visible"/>
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </Button.Style>
                </Button>
                </Grid>
            </DataTemplate>
        </TabControl.ItemTemplate>
        <TabControl.ContentTemplate>
            <!-- this is the body of the TabItem template-->
            <DataTemplate>
                <TextBlock Text="{Binding SomeServerPropertyToDisplay}" />
            </DataTemplate>
        </TabControl.ContentTemplate>
    </TabControl>
    <DataGrid ItemsSource="{Binding LogMessages}" Grid.Row="1"/>
    <StackPanel Orientation="Horizontal" Grid.Row="2">
        <TextBlock Text="{Binding Path=SelectedServer.Name, StringFormat=Current server: {0}}"/>
        <Button Command="{Binding Connect, Mode=OneTime}" Content="Connect"/>
        <Button Command="{Binding Disconnect, Mode=OneTime}" Content="Disconnect"/>
    </StackPanel>
</Grid>

来自我的服务器的请求有效,但是从Facebook开始,它不是,这是我的[ImplementPropertyChanged] public partial class Window1 : Window { MyViewModel VM; public Window1() { InitializeComponent(); this.VM = new MyViewModel(); this.DataContext = this.VM; } } [ImplementPropertyChanged] public class MyViewModel { public ObservableCollection<LogMessage> LogMessages { get; set; } public ObservableCollection<ServerTab> AllServers { get; set; } public ServerTab SelectedServer { get; set; } public MyViewModel() { this.AllServers = new ObservableCollection<ServerTab>(); this.AllServers.Add(new ServerTab { Name = "+" }); this.LogMessages = new ObservableCollection<LogMessage>(); } private ICommand _AddNew; public ICommand AddNew { get { return _AddNew ?? (_AddNew = new DelegateCommand(a => AddNewCommand(a))); }} private void AddNewCommand(object item) { var senderItem = (ServerTab)item; if (senderItem.Name == "+") { var newItem = new ServerTab { Name = "Name " + (this.AllServers.Count) }; this.AllServers.Remove(senderItem); this.AllServers.Add(newItem); this.AllServers.Add(senderItem); this.LogMessages.Add(new LogMessage { Time = DateTime.Now, Message = newItem.Name + " added" }); } } private ICommand _Connect; public ICommand Connect{ get { return _Connect ?? (_Connect = new DelegateCommand(a => ConnectCommand(a))); }} private void ConnectCommand(object item) { this.LogMessages.Add(new LogMessage { Time = DateTime.Now, Message = this.SelectedServer.Name+" connected" }); } private ICommand _Disconnect; public ICommand Disconnect{ get { return _Disconnect ?? (_Disconnect = new DelegateCommand(a => DisconnectCommand(a))); }} private void DisconnectCommand(object item) { this.LogMessages.Add(new LogMessage { Time = DateTime.Now, Message = this.SelectedServer.Name +" disconnected" }); } } [ImplementPropertyChanged] public class ServerTab { public string Name { get; set; } public string SomeServerPropertyToDisplay { get; set; } public ServerTab() { SomeServerPropertyToDisplay = DateTime.Now.Ticks.ToString(); } } [ImplementPropertyChanged] public class LogMessage { public DateTime Time { get; set; } public string Message { get; set; } } 文件:

https://apps.facebook.com/mygame

API使用slim framework(php)完成,我的服务器是Apache。 我尝试了很多选项,例如在function login(token) { $.ajax({ url: 'https://myurl/api/login', method: 'get', headers: {"Authorization": "Bearer " + token}, contentType: "application/json", beforeSend: function(xhr) { xhr.setRequestHeader("Authorization", "Bearer " + token); }, success: function(data, textStatus, jqXHR) { // To next state }, error: function (jqXHR, textStatus, errorThrown) { // Error } }); } 或AJAX请求中设置标题,但我没有实现它。 我怎么能这样做?

0 个答案:

没有答案