Если при попытке зайти на страницу веб интерфейса модуля интеграции бразуер возвращает ошибку Failed to fetch, значит были закэшированы старые данные.
Нужно очистить кэш браузера для страницы веб интерфейса модуля интеграции.
Очистка кэша в Google Chrome:
-
1.
Откройте инструменты разработчика: Ctrl+Shift+I
-
2.
Теперь, оставив панель открытой, кликните левой кнопкой мыши на кнопку «Обновить» (рядом со строкой адреса) и не отпускайте кнопку.
-
3.
Через несколько секунд вы увидите выпадающее меню в котором будет пункт: Очистка кэша и аппаратная перезагрузка.
Также чтобы перезагрузить страницу без использования файлов кэша, можно воспользоваться комбинацией клавиш Ctrl+F5
или Ctrl+Shift+R
.
Пишу курсовой проект — веб-приложение (Node.js, express, React, Postgre). В процессе понадобилось добавить в проект авторизацию, столкнулась с проблемой еще на этапе организации POST-запросов:
запрос успешно уходит на сервер, на сервере по логину находится пользователь в БД, определяется для него токен (по логам на сервере — до этого момента все в порядке), но ответ с сервера на клиент корректный приходит (в лучшем случае) попытки с 10 ввести логин и пароль.
В остальное время выбрасывается «TypeError: Failed to fetch», а статус запроса — «отменен».
Запрос на клиенте:
export const login = async (login, password) => {
let data
try{
const response=await fetch('http://localhost:5000/api/user/login', {
method: 'POST',
body: JSON.stringify({
login: login,
password: password
}),
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
})
data = await response.json()
if(!response.ok) {
throw new Error(data.message || 'Error')
}
console.log(data)
} catch (error) {
console.error(error)
}
return (data)
}
Обработка на сервере:
async login(req, res) {
try{
const {login, password} = req.body
const user = await User.findOne({where: {login}})
if (!user) {
return res.json({ message: 'Пользователь не найден' })
}
let comparePassword = bcrypt.compareSync(password, user.password)
if (!comparePassword) {
return res.json({ message: 'Указан неверный пароль'})
}
const accountType = user.login === "admin" ? true : false
const token =jwt.sign(
{
login: user.login,
accountType:accountType
},
"TEST_KEY",
{expiresIn: '24h'}
)
console.log(token)
return res.json({token})
}
catch (e) {
console.log("error")
console.log(e)
}
}
POST-запрос на добавление новых пользователей работает аналогично: в БД пользователь записывается, а при попытке вернуть с сервера что-то вроде response.status(201).json({message: 'Пользователь создан'})
— снова «Failed to fetch».
С Get-запросами подобной проблемы не возникает.
Не знаю, как добиться стабильности работы запросов: никак не могу понять, какая закономерность в случаях, когда ответ до клиента все-таки доходит, а когда — нет. Была бы катастрофически благодарна за помощь
Компонент с формой
export const ClientMain = () => {
const [newUser, setNewUser] = useState({
userName: "",
password: "",
})
const changeNewUserHandler = (event) => {
setNewUser({ ...newUser, [event.target.name]: event.target.value })
}
let checkInput = (() => {
let isDisabled = document.getElementById("password") && document.getElementById("userName")
? !(
document.getElementById("password").checkValidity() &&
document.getElementById("userName").checkValidity()
)
: true
return isDisabled
})
const clickLogin = async () => {
await login(newUser.userName, newUser.password)
}
return (
<>
<div id="loginCard" className="modal-main">
{/* <div className="modal-content" id="modal-content"> */}
<div className="window-user">
<form className="fields-user" id="window">
<input
className="input-user"
placeholder="Логин"
type="text"
id="userName"
name="userName"
value={newUser.userName}
onChange={changeNewUserHandler}
required
pattern="^.{4,16}$"
/>
<input
className="input-user"
placeholder="Пароль"
type="text"
id="password"
name="password"
value={newUser.password}
onChange={changeNewUserHandler}
required
pattern="^.{8,16}$"
/>
<div className="errorsBox">
<p className="errorMessage-main" id="errorLogin">
Логин должен содержать от 4 до 16 символов.
</p>
<p className="errorMessage-main" id="errorPassword">
Пароль должен содержать от 8 до 16 символов.
</p>
</div>
<input
type="submit"
className="addButton"
value="Войти"
disabled={checkInput()}
onClick={clickLogin}
></input>
</form>
</div>
</div>
</>
)
}
The most common cause for this error is CORS restrictions. If the API is hosted on a different domain or port than my React app, I may need to configure CORS headers on the server to allow my app to access it.
Here is my code that throws the error.
useEffect(() => {
fetch("http://localhost:8090/core/1/home")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))
}, [])
Uncaught (promise) TypeError: Failed to fetch
at MyReactComponent.js:6:1
at commitHookEffectListMount (react-dom.development.js:23150:1)
at commitPassiveMountOnFiber (react-dom.development.js:24926:1)
at commitPassiveMountEffects_complete (react-dom.development.js:24891:1)
at commitPassiveMountEffects_begin (react-dom.development.js:24878:1)
at commitPassiveMountEffects (react-dom.development.js:24866:1)
at flushPassiveEffectsImpl (react-dom.development.js:27039:1)
at flushPassiveEffects (react-dom.development.js:26984:1)
at react-dom.development.js:26769:1
at workLoop (scheduler.development.js:266:1)
(anonymous)
How to fix it?
1. Configure CORS headers on the server to allow your app to access it.
If your API is built with SpringBoot, add @CrossOrigin annotation to the controller.
@RestController
@RequestMapping("/core/1")
@CrossOrigin(origins = "*")
public class HomeController {
@GetMapping("/home")
public String home() {
return "Hello, world!";
}
}
2. In Python, I can enable CORS by adding appropriate headers to the HTTP response returned by the API endpoints. The headers include Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers, and Access-Control-Allow-Credentials.
Here’s an example of how to enable CORS for all origins in a Flask API.
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api/data')
def get_data():
data = {'key': 'value'}
response = jsonify(data)
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
response.headers.add('Access-Control-Allow-Credentials', 'true')
return response
if __name__ == '__main__':
app.run()
3. In .NET, I can configure CORS for specific endpoints by adding the EnableCors attribute to the controller or action methods.
using Microsoft.AspNetCore.Mvc;
namespace YourAppNamespace.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class HomeController : ControllerBase
{
[HttpGet]
[EnableCors("AllowAllOrigins")]
public ActionResult<string> Get()
{
return "Hello, world!";
}
}
}
4. In Node.js, I can enable CORS using the CORS package or setting the appropriate headers in the Node.js application.
In this example, the CORS middleware is used to enable CORS for all routes in the application.
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.get('/api/data', (req, res) => {
const data = { message: 'Hello, world!' };
res.json(data);
});
app.listen(8080, () => {
console.log('Server listening on port 8080');
});
If I want to allow CORS only for specific domains:
const express = require('express');
const cors = require('cors');
const app = express();
const corsOptions = {
origin: 'http://example.com'
};
app.use(cors(corsOptions));
app.get('/api/data', (req, res) => {
const data = { message: 'Hello, world!' };
res.json(data);
});
app.listen(8080, () => {
console.log('Server listening on port 8080');
});
There are other factors that can contribute to this issue besides CORS. They are:
- Make sure the URL is correct and valid. Check if you can access the URL directly from the browser to confirm that it’s available.
- Check if the server is running and accessible. Confirm that the API is currently online and accepting requests.
- Ensure that the fetch request is being made with the correct HTTP method. By default, fetch uses the GET method, but if the API requires a different method (such as POST, PUT, DELETE), you need to specify it in the fetch options.
- Verify if there is any authentication required to access the API. If the API requires authentication, make sure you are sending the necessary credentials (such as an access token) in the fetch request headers.
POST https://localhost:5000/add-user/ net::ERR_CONNECTION_CLOSED
Uncaught (in promise) TypeError: Failed to fetch
Делаю запрос через свой хук, подскажите пожалуйста в чем может быть проблема?
CLIENT
const useDb = useDatabase();
<button onClick={() => useDb.addUser(userInfo.email, userInfo.name, userInfo.password)}>Submit</button>
HOOK
export default function useDatabase() {
function addUser(email, name, password) {
let newUser = {
email: email,
name: name,
password: password
}
fetch(`https://localhost:5000/add-user/`, {
method: 'POST',
headers: {'Content-type': 'application/json'},
body: JSON.stringify(newUser)
}).then(data => console.log(data));
}
return {addUser}
}
SERVER
const dotenv = require('dotenv');
const dbService = require('./dbService');
const cors = require('cors');
dotenv.config();
const express = require('express');
app = express();
app.use(cors());
app.use(express.json());
const port = process.env.SERVER_PORT;
app.listen(port, () => {console.log('server started on port ' + port)})
app.post('/add-user', function(req, res) {
console.log(req.body)
});
Typeerror failed to fetch: The “TypeError: Failed to fetch” error can arise for several reasons:
- Passing an incorrect or incomplete URL to the
fetch()
method. - The server to which you are making a request does not return the correct CORS headers.
- The URL has an incorrect protocol.
- Passing a wrong method or headers to the
fetch()
method.
Let us see the examples to know how this error occurs and try to fix them.
async function getEmployDetails() { try { // Here we are passing incorrect/incomplete URL. // Hence TypeError: Failed to fetch occurs const url_response = await fetch('https://jhgdwyhnzlk.com/udybsjhdir'); // check if the status of url response is not okay (failed) if (!url_response.ok) { throw new Error(`Error! status: ${url_response.status}`); } // if the response is okay then apply the json() function on url response const output = await url_response.json(); // return the result(response) from the url return output; } catch (error) { // If any error occurs then in the catch block print it console.log(error); } } // Call the getEmployDetails() function getEmployDetails();
Explanation:
Since the URL we passed to the fetch method was incorrect, we received two errors:
- CORS: No ‘Access-Control-Allow-Origin’ header is present on the requested resource
- TypeError: Failed to fetch
Fixing “TypeError: Failed to fetch” Error
Typeerror: failed to fetch: Check that the URL that you are passing to the fetch() method is complete and valid. Do the following for this:
- Include the protocol, for example,
https://
orhttp://
if you are testing on localhost without an SSL certificate. - The URL path must be correct, for example, /btechgeeks.
- The HTTP method must be appropriate for the path specified.
- If you misspell any of the configuration, such as a property in the headers object or an HTTP method, you will receive an error.
To resolve the "TypeError: Failed to fetch,"
ensure that the correct configuration is sent to the fetch
method, including the URL, HTTP method, headers, and that the server to whom you are making a request is setting the necessary CORS headers with the response.
// async function getWebsiteDetails() { try { // Pass the url as an argument to the fetch() function const url_response = await fetch('https://randomuser.me/api/', { // Add request method method: 'GET', // Add headers of the request using the accept headers: { accept: 'application/json', }, }); // check if the status of url response is not okay (failed) if (!url_response.ok) { throw new Error(`Error! status: ${url_response.status}`); } // if the response is okay then apply the json() function on url response and store the response in a variable const output = await response.json(); // return the result(response) from the url return output; } catch (error) { // If any error occurs then in the catch block print it console.log(error); } } // Call the getEmployDetails() function getWebsiteDetails();
NOTE:
If we perform a POST, PUT, or PATCH, make sure the body is passed to the JSON.stringify() method in the fetch method call.
If the configuration that you pass to the fetch method is correct, check to see if your server is sending the correct/valid CORS headers in the response.
Along with the response, the server must set the following CORS headers:
# Paste your domain/server link below like http://localhost:5000 Access-Control-Allow-Origin: http://example.com Access-Control-Allow-Methods: POST, PUT, PATCH, GET, DELETE, OPTIONS Access-Control-Allow-Headers: Origin, X-Api-Key, X-Requested-With, Content-Type, Accept, Authorization
Depending on your use case, you may need to adjust the values, by opening the Network tab in your browser, clicking on the request, and seeing if your server is setting these CORS-related headers.
The headings are as follows:
Access-Control-Allow-Origin: It specifies which origins are permitted/allowed to make requests to the server.
Access-Control-Allow-Methods: It specifies which HTTP methods the origins are permitted to use when making requests to the server.
Access-Control-Allow-Headers: It specifies which HTTP headers origins are permitted to use when making requests to the server.