Skip to content

Instantly share code, notes, and snippets.

@newdecline
Last active October 21, 2019 06:19
Show Gist options
  • Save newdecline/8d3dfa4639dc86c69613a1bb1012e524 to your computer and use it in GitHub Desktop.
Save newdecline/8d3dfa4639dc86c69613a1bb1012e524 to your computer and use it in GitHub Desktop.
export const fetchApi = async (url, init = {}) => {
const result = await fetch(`${baseUrl}${url}`,{...init});
if (!result.ok) {
throw new Error(`Ошибка при запросе ${url}, код ${result.status}`);
}
return await result.json();
};
import React from 'react';
import {fetchApi} from './services/api/fetchApi';
import './scss/styles.scss';
export const App = () => {
const onSubmit = (e) => {
e.preventDefault();
fetchApi('/sites')
.then(res => {console.log(res)})
.catch(err => {console.log(err)});
console.log('submitted');
};
return (
<div className='app'>
<form className='form' onSubmit={onSubmit}>
<input className="form__input" type='text'/>
<input className="form__input" type='text'/>
<input className="form__input" type='text'/>
<input className="form__input" type='text'/>
<button type="submit" className="form__submit">обновить</button>
</form>
</div>
);
};
Server.js
const express = require('express');
const app = express();
const port = 3001;
app.get('/api/sites', (request, response) => {
response.send({
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
});
});
app.use((err, request, response, next) => {
console.log(err);
response.status(500).send('Ошибка на сервере');
})
app.listen(port, (err) => {
if (err) {
return console.log('Что то пошло не так', err);
}
console.log(`Веб-сервер запущен на порту ${port}`);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment