Estoy usando News API en ReactJS para obtener noticias usando fetch API.
FRAGMENTO DE CÓDIGO
const url = `https://newsapi.org/v2/top-headlines?country=in&category=${this.props.category}&pageSize=${this.state.pageSize}&page=${this.state.page}`; let data = await fetch(url);Pero cuando lo ejecuto en el host local, dio un error 400 diciendo:
{status: 'error', code: 'userAgentMissing', message: 'Please set your User-Agent header to identify your application. Anonymous requests are not allowed.'}Cuando busqué lo mismo en Stack Overflow, obtuve un enlace de un problema similar aquí:
Error de falta de agente de usuario al realizar una solicitud de obtención a una API
Luego agregué el encabezado User-Agent en el argumento de la API de búsqueda:
FRAGMENTO DE CÓDIGO
headers = new Headers({ "X-Api-Key": this.apiKey, "User-Agent": navigator.userAgent }); const url = `https://newsapi.org/v2/top-headlines?country=in&category=${this.props.category}&pageSize=${this.state.pageSize}&page=${this.state.page}`; let data = await fetch(url, { headers: this.headers });Pero aún muestra el mismo error:
{status: 'error', code: 'userAgentMissing', message: 'Please set your User-Agent header to identify your application. Anonymous requests are not allowed.'}Este error solicita "User-Agent" en el encabezado de la solicitud, ¡pero ya está allí! Cuando miré en la sección de red del navegador Chrome.
Entonces, ¿cuál es exactamente el problema? ¿Y cómo solucionar este problema?