Api, CORS, random image, javascript.

Posts: 3 · Views: 107
  • 37751

    Hi, it's not possible to use your api from javascript in browser. I just want to load some random wallpaper as example chrome dev console: fetch("https://wallhaven.cc/api/v1/search?seed=mQkrgy") But browser blocks it

    Access to fetch at 'https://wallhaven.cc/api/v1/search?seed=mQkrgy' 
    from origin 'https://novelfull.com' 
    has been blocked by CORS policy: 
       No 'Access-Control-Allow-Origin' header is present on the requested resource. 
       If an opaque response serves your needs, 
       set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

    As I know some services provide endpoint , which redirected to image itself. And this endpoint not blocked by cors.

    https://random.imagecdn.app/1920/1080 https://random.danielpetrica.com/api/random https://api.nekosapi.com/v4/images/random/file e.t.c.

    It's possible to include this to css without any json parsing. div.style.background = 'background: url("https://random.imagecdn.app/1920/1080")'

    But I can't find way to do such things with your site. Only disabling browser cross domain policy, which leads to vulnerability.

  • 37759

    Yeah, It's an annoying problem.

    My solution was to just put a server in between wallhaven and the webpage.

    A quick and dirty example is this:

    import express from 'express'
    import cors from 'cors'
    
    let app = express()
    
    app.use(cors())
    
    app.get('/', async (req, res) => {
        let data_req = await fetch(req.query.url)
        res.setHeader('Content-Type', data_req.headers.get('Content-Type')).send(
            Buffer.from(await data_req.arrayBuffer())
        )
    })
    
    app.listen(3000, () => {
        console.log('> Listening on port 3000')
    })

    Then you can just fetch http://localhost:3000/?url=https://wallhaven.cc/api/v1/search?seed=mQkrgy instead of https://wallhaven.cc/api/v1/search?seed=mQkrgy and it should work.

  • 37761

    Qwertyyyyy Yeah, I know. But mine script works on multiple devices: IPad, PC. Probably I’ll share script. It’s a headache. It’s easier to prepare json with several thousand urls and load it.

Message