最近在專案上碰Solid-auth-client,他是讓使用者能自己授權存取pod server,並且含有Auth功能,詳細Solid。有項功能是讀寫自己的pod,他是採用fetch的方式,也因為很少用fetch大多用axios,加上Solid-auth-client的架構問題所以採坑了一陣子。紀錄一下以免以後又遇到。
Solid-auth-client裡有分public、private的地方可以寫入,但在Auth登入時需要給授權,是否能讀寫,否則大家都不能操作,public是能夠大家都能Read,而Write則是需要授權。
private的fetch write
solid.auth
.fetch("https://urusername.solid.community/private/foldername", {
method: "PUT", // or 'DELETE'(刪除)
headers: {
"Content-Type": "application/json",//application/json OR text/turtle
Link: '<http://www.w3.org/ns/ldp#BasicContainer>;rel="type"',
},
body:JSON.stringify(Data)//fetch json need to string or file can upload
})
.then((response) => {
return response.text();//fetch response need to arrayBuffer() blob()formData()json()text()
})
.then(data => {
console.log(data);
})
.catch(error => console.log("Error: " + JSON.stringify(error)));
}
他是透過PUT方式來創建他的folder,並不是POST過去就可以,而fetch的方式必須將傳輸data去轉成string,像平時的axios就能夠直接傳送json過去,或加上qs轉換。
而fetch的 Response 物件中的 body 屬性提供了一個 ReadableStream 的實體,這個階段我們無法直接讀取資料內容。
需透過arrayBuffer()、blob()、formData()、json()、text()做轉換。
而Read Public的資料夾就單純多了,直接fetch網址或用axios就能解決。
Read private
solid.auth.fetch("https://lizongwei.solid.community/private/test", {
})
.then(response => {return response.text()})
.then(data => console.log(data))
.catch(error => console.error(error));