_leoatliang 2024-10-31 20:52 采纳率: 60%
浏览 39
已结题

js怎么实现跨域问题

1、描述问题

我有一个django项目,其中的一个页面,背景图片是由css写的,就是底下这个 background-image

.img:before {
  content: "";
  position: absolute;
  right: 0;
  top: 0;
  width: 900px;
  height: 100%;
  background-image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/142996/sections-3.jpg");
  background-size: cover;
  transition: transform 1.2s ease-in-out;
}

2、现在情况

我自己手写了一个js,所以现在是由js文件控制这个背景图片,并且可以成功运行出图

function updateBackgroundImage(url) {
    // 查找已有的动态样式元素,若存在则先删除
    const existingStyle = document.getElementById('dynamic-bg-style');
    if (existingStyle) {
        existingStyle.remove();
    }

    // 创建新的 <style> 元素
    const style = document.createElement('style');
    style.id = 'dynamic-bg-style';
    style.textContent = `.img:before { background-image: url('${url}'); }`;
    document.head.appendChild(style);
}

updateBackgroundImage('https://s3-us-west-2.amazonaws.com/s.cdpn.io/142996/sections-3.jpg');

3、!问题

我不想让图片太单一,可以每天换个背景图片,所以想到了必应每日壁纸的api,如下:

https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1

4、想法

我想使用js访问这个api接口,然后拼接成真实的图片地址,然后通过js使用,最后实现换图的操作;但这好像涉及到了js的跨域问题,我的项目只求在本地使用,小项目,不上线

  • 写回答

35条回答 默认 最新

  • 专家-赤兔[在线] 优质创作者: 编程框架技术领域 2024-10-31 20:53
    关注
    获得0.40元问题酬金

    以下回复引自免费微信小程序:皆我百晓生。 如问题解决,还请采纳。如仍有疑问,请回复留言或私信博主,以便获得更精准的帮助。

    为了解决你的跨域问题并实现每日更换背景图片,可以考虑使用JSONP或代理服务。以下是两种方法:

    方法一:使用JSONP

    Bing的API不支持跨域请求,但你可以通过JSONP绕过跨域问题。JSONP是通过在HTML页面中动态加载带有回调函数的<script>标签来实现的。

    但是,Bing API可能不支持JSONP格式。如果支持,可以按照以下方法实现:

    function fetchImage() {
        const script = document.createElement('script');
        script.src = 'https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&callback=setBackgroundImage';
        document.body.appendChild(script);
    }
    
    function setBackgroundImage(data) {
        const baseUrl = "https://cn.bing.com";
        const imgUrl = baseUrl + data.images[0].url;
        updateBackgroundImage(imgUrl);
    }
    
    fetchImage();
    

    方法二:使用本地代理绕过跨域

    由于项目在本地运行,可以在Django中配置一个视图作为代理,通过服务器请求Bing的API,然后将数据返回给前端。这可以避免跨域问题。

    1. 在Django中创建代理视图

      import requests
      from django.http import JsonResponse
      
      def proxy_bing_wallpaper(request):
          url = 'https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1'
          response = requests.get(url)
          return JsonResponse(response.json())
      
    2. 配置URL路由

      urls.py中添加路由:

      from django.urls import path
      from .views import proxy_bing_wallpaper
      
      urlpatterns = [
          path('proxy-bing/', proxy_bing_wallpaper, name='proxy_bing'),
      ]
      
    3. 前端JavaScript请求代理API

      fetch('/proxy-bing/')
          .then(response => response.json())
          .then(data => {
              const baseUrl = "https://cn.bing.com";
              const imgUrl = baseUrl + data.images[0].url;
              updateBackgroundImage(imgUrl);
          })
          .catch(error => console.error('Error fetching image:', error));
      

    以上方法可以帮助你在本地实现每日更换Bing壁纸的功能,同时绕过跨域限制。

    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 11月8日
  • 创建了问题 10月31日