我想从fastify中获取图像并以svelte显示它,当我访问服务器url(http://localhost:3000/image/Darkaron.jpg)时,它工作了,但是当我从svelte (http://localhost:8080/image/Darkaron.jpg)访问它时,它拒绝显示并给出这个错误。
https://i.postimg.cc/HsKwYkpK/image-error.png
服务器代码:
import fastify from "fastify"
import fstatic from "@fastify/static"
import cors from "@fastify/cors";
const imagePath = '/storage'
type FileResponse = {
filename: string
}
const server = fastify({
logger: true
})
server.register(fstatic, {
root: imagePath
})
server.register(FastifyMultipart)
server.register(cors, {
origin: "*",
methods: ["OPTIONS", "GET", "POST"]
})
server.get("/image/:filename", (req, res) => {
res.sendFile((req.params as FileResponse).filename)
})
const start = async () => {
try {
await server.listen(3000)
} catch (err) {
server.log.error(err)
process.exit(1)
}
}
start()svelte码
<script lang="ts">
import axios from "axios";
import { onMount } from "svelte";
onMount(async function() {
let res = await axios({
method: 'GET',
url: 'http://localhost:3000/image/Darkaron.jpg'
})
console.log(res.data)
})
</script>
<div>check console</div>发布于 2022-05-29 19:17:27
在您的客户端应用程序中,尝试使用文件index.ts创建档案api。
import axios from "axios";
export async function getImage() {
let res = await axios({
method: 'GET',
url: 'http://localhost:3000/image/Darkaron.jpg'
})
console.log(res.data)
}在svelte文件中导入api。
<script lang="ts">
import { getImage } from 'your path to api';
</script>
<div>check console</div>https://stackoverflow.com/questions/72415740
复制相似问题