export const postComment = async (photo_id, comment) => { return await fetch(`${apiRoot}/photos/${photo_id}/comments`, { ...defaultOptions(), method: 'POST', body: JSON.stringify({ comment }), }) }
export const signIn = async (email, password) => { return await fetch(`${apiRoot}/users/sign_in`, { ...defaultOptions(), method: 'POST', body: JSON.stringify({ user: { email, password } }), }) }
export const updatePhoto = async (photo_id, photo) => { return await fetch(`${apiRoot}/admin/photos/${photo_id}`, { ...defaultOptions(), method: 'PUT', body: JSON.stringify(photo), }) }
export const sendPasswordReset = async email => { return await fetch(`${apiRoot}/users/password`, { ...defaultOptions(), method: 'POST', body: JSON.stringify({ user: { email } }) }) }
export const signUp = async user => { return await fetch(`${apiRoot}/users`, { ...defaultOptions(), method: 'POST', body: JSON.stringify({ user: { ...user, provider: "email" } }), }) }
export const API_DELETE = (url) => { var request = new Request(url, { method: 'DELETE', mode: 'cors', headers: new Headers({ 'Content-Type': 'text/plain', }) }); return fetch(request).then(res => { if ( res.status < 400 ) { return res.json() } else { return new Promise((resolve, reject) => { res.text().then(text => { try { const json = JSON.parse(text) reject(new Error(json)) } catch(ex) { reject(new Error(text)) } }) }) } }) }
handleSubmit = (e) => { e.preventDefault() this.setState({disabled: true}) const form = new FormData(e.target) fetch('api/trabajo',{ method: 'POST', body: form }) .then(r => { if (r.status === 200){ this.setState({ success: true }) setTimeout(() => this.setState({ disabled: false, success: false }), 4000) } else { this.setState({ error: true }) setTimeout(() => this.setState({ disabled: false, error: false }), 4000) } }) }
export const resetPassword = async params => { return await fetch(`${apiRoot}/users/password`, { ...defaultOptions(), method: 'PATCH', body: JSON.stringify({ user: params }) }) }
export const signOut = async (request = {}) => { const response = await fetch(`${apiRoot}/users/sign_out`, { ...defaultOptions(), method: 'DELETE', }) return response.status === 204 }
static async getInitialProps({ query }) { const { url } = query const response = await fetch(`${API_URL}/stats?url=${url}`) const stats = await response.json() return { uri: url, ...stats } }
async function get(url) { const options = auth ? { headers: { Authorization: `Basic ${btoa(auth)}` } } : {}; const res = await fetch(url, options); const json = await res.json(); return json; }
async componentDidMount() { try { const request = await fetch(this.props.url); const response = await request.text(); await this.setState({ markdown: response, loading: false }); } catch (err) { console.log(err); } }
componentDidMount () { Flickity = require('flickity') const lang = localStorage.getItem('lang') const apiUrl = `api/publicaciones?lang=${lang === null ? 'es' : lang}` fetch(apiUrl) .then( r => r.json() ) .then( data => { this.setState({ posts: data }) }) }
Post.getInitialProps = async function (context) { const { id } = context.query const res = await fetch(`https://api.tvmaze.com/shows/${id}`) const show = await res.json() console.log(`Fetched show: ${show.name}`) return { show } }
export default async function fetchFromBackend(req, path) { const fetchOptions = { method: 'GET', headers: { 'Accept': 'application/json', }, } if (req) { // we are in node.js const backendUrl = process.env.BACKEND_URL || 'http://127.0.0.1:5000' fetchOptions.headers['Cookie'] = req.headers['cookie'] const res = await fetch(backendUrl + path, fetchOptions) return await res.json() } else { // we are in browser fetchOptions.credentials = 'same-origin' const res = await fetch(path, fetchOptions) return await res.json() } }
async requestOverviewContent() { try { const overviewPromise = await fetch(contentsOfLaravel.overview); const overview = await overviewPromise.text(); await this.setState({ overview, overviewLoading: false, }); } catch (err) { console.log(err); } }
const getJson = async (path, request = {}) => { const response = await fetch(`${apiRoot}${path}`, { credentials: 'include', headers: { 'Cookie': request.headers && request.headers.cookie, 'Content-Type': 'application/json', 'Accept': 'application/json', }, }) const data = await response.json() return { ...data, csrfToken: csrfTokenFromHeader(response) } }
static async getInitialProps ({ req, query, pathname, isVirtualCall }) { const url = format({ pathname, query }) // if we're not running server side // get the props from sessionStorage using the pathname + query as key // if we got something return it as an object if (!req) { const props = window.sessionStorage.getItem(url) if (props) { return JSON.parse(props) } } // fetch data as usual const responses = await Promise.all([ fetch(`https://jsonplaceholder.typicode.com/posts/${query.id}`), fetch(`https://jsonplaceholder.typicode.com/posts/${query.id}/comments`) ]) const [article, comments] = await Promise.all( responses.map(response => response.json()) ) const user = await fetch( `https://jsonplaceholder.typicode.com/users/${article.userId}` ).then(response => response.json()) const props = { article, comments, user } // if the method is being called by our Link component // save props on sessionStorage using the full url (pathname + query) // as key and the serialized props as value if (isVirtualCall) { window.sessionStorage.setItem(url, JSON.stringify(props)) } return props }
static async getInitialProps(ctx) { const response = await fetch( GIT_SCRY_CHECK_LOGGED_IN, { headers: { cookie: ctx.req.headers.cookie, }, }, ); const { loggedIn } = await response.json(); return { loggedIn }; }
static async getInitialProps ({ req, query }) { const isServer = !!req console.log('getInitialProps called:', isServer ? 'server' : 'client') if (isServer) { // When being rendered server-side, we have access to our data in query that we put there in routes/item.js, // saving us an http call. Note that if we were to try to require('../operations/get-item') here, // it would result in a webpack error. return { item: query.itemData } } else { // On the client, we should fetch the data remotely const res = await fetch('/_data/item', {headers: {'Accept': 'application/json'}}) const json = await res.json() return { item: json } } }
const callUrlWithMethod = async ev => { try { ev.preventDefault(); const res = await fetch(baseUrl + url, { method }); if (res.ok) { setState("ok"); setResponse( res.status === 204 ? "STATUS CODE: 204" : (await res.json()).text ); } else { throw await res.text(); } } catch (err) { setState("error"); setResponse(err.toString()); } };
export const FETCH_JSON = (url, method = 'get', headers = {accept: 'application/json'}) => fetch(url, { method, headers }) .then(res => { if ( res.status < 400 ) { return res.json() } else { return new Promise((resolve, reject) => { res.text().then(text => { try { const json = JSON.parse(text) reject(new Error(json)) } catch(ex) { reject(new Error(text)) } }) }) } })
export const POST_JSON = (url, data, method = 'post', headers = {'Content-Type': 'application/x-www-form-urlencoded'}, json=false) => { let str = '' if (json) { for (let key in data) { if (str != '') { str += '&' } str += `${key}=${encodeURIComponent(data[key])}` } } else { str = data headers = { ...headers, 'Content-Type': 'application/json' } } return fetch(url, { method: method, headers: headers, body: str, }).then(res => { if ( res.status < 400 ) { return res.json() } else { return new Promise((resolve, reject) => { res.text().then(text => { try { const json = JSON.parse(text) reject(new Error(json)) } catch(ex) { reject(new Error(text)) } }) }) } }) }
async function getJWK() { const res = await fetch(`https://${settings.domain}/.well-known/jwks.json`); const jwk = await res.json(); return jwk; }
export const deleteFavorite = async (photo_id, plus_one_id) => { return await fetch(`${apiRoot}/photos/${photo_id}/plus_ones/${plus_one_id}`, { ...defaultOptions(), method: 'DELETE', }) }
static async getInitialProps ({ query }) { // fetch single post detail const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${query.id}`) const post = await response.json() return { ...post } }
const fetch = require('isomorphic-unfetch') module.exports = { async exportPathMap () { // we fetch our list of posts, this allow us to dynamically generate the exported pages const response = await fetch('https://jsonplaceholder.typicode.com/posts?_page=1') const postList = await response.json() // tranform the list of posts into a map of pages with the pathname `/post/:id` const pages = postList.reduce( (pages, post) => Object.assign({}, pages, { [`/post/${post.id}`]: { page: '/post', query: { id: post.id } } }), {}, ) // combine the map of post pages with the home return Object.assign({}, pages, { '/': { page: '/' } }) } }
export const createFavorite = async (photo_id) => { return await fetch(`${apiRoot}/photos/${photo_id}/plus_ones`, { ...defaultOptions(), method: 'POST', }) }
function fetchJson(urlPath: string, options?: Object): Promise<any> { return fetch(getApiUrl(urlPath), options).then(parseResponse); }
MainImage.getInitialProps = async function() { const res = await fetch('http://localhost:7000/_/files/5') const data = await res.json() console.log(data); return { images: data } }