我在快递中使用svelte / sapper。
我在routes/billing/index.js
中有一个api
它需要从customers/[customernumber]/detections.js
提取数据
我的问题是如何使用相对URL从route文件夹中的内部api获取数据
async function getDataFromGateway(customerNumber) {
if (typeof fetch !== 'function') {
global.fetch = require('node-fetch')
}
const data = await fetch(`http://localhost:19052/customers/${customerNumber}/detections`)
.then(res => res.json())
.catch(error => {
console.log(error)
return error
}
)
return data
}
有没有一种方法可以使用相对网址
答案 0 :(得分:3)
最简单的方法是使用preload
在this.fetch
内部获取此数据,因为无论在服务器还是客户端上运行,都会自动以相同的方式处理相对URL:
<script context="module">
export async function preload(page, session) {
const r = await this.fetch(`customers/${getCustomerNumber(session)}/detections`);
const data = await r.json();
return {
foo: data.foo
};
}
</script>
如果由于某种原因无法实现,则可能需要配置环境变量,例如BASE_URL
:
async function getDataFromGateway(customerNumber) {
if (typeof fetch !== 'function') {
global.fetch = require('node-fetch')
}
const data = await fetch(`${process.env.BASE_URL}/customers/${customerNumber}/detections`)
.then(res => res.json())
.catch(error => {
console.log(error)
return error
}
)
return data
}