api 在 react redux 中调用的 400 错误在示例中工作正常
400 error for api call in react redux working fine in an example
- 我正在努力学习 react redux api 调用
- 所以我举了一个例子并在 stackblitz 中实现,但我收到以下错误
GET https://newsapi.org/v1/articles?%20%20%20%20%20%20%20source=bbc-news&apiKey=c39a26d9c12f48dba2a5c00e35684ecc 400(错误请求)
- 你能告诉我怎么解决吗
- 在下面提供我的代码和 stackblitz
https://medium.com/@lavitr01051977/basic-react-redux-app-with-async-call-to-api-e478e6e0c48b
https://stackblitz.com/edit/react-redux-realworld-4ldsnt?file=components/ChannelsField.js
export function fetchPosts(channel) {
return function (dispatch) {
dispatch(requestPosts());
return fetch(`https://newsapi.org/v1/articles?
source=${channel}&apiKey=${MY_API_KEY}`)
.then(
response => response.json(),
error => console.log('An error occurred.', error),
)
.then((json) => {
dispatch(receivedPosts(json));
},
);
};
}
看起来您的请求在 ? 之间有额外的空格 (%20)和导致 400 错误请求的来源。将您的函数更改为以下内容,它应该可以工作:
export function fetchPosts(channel) {
return function (dispatch) {
dispatch(requestPosts());
return fetch(`https://newsapi.org/v1/articles?source=${channel}&apiKey=${MY_API_KEY}`)
.then(response => response.json(),
error => console.log('An error occurred.', error),
)
.then((json) => {
dispatch(receivedPosts(json));
},);
};
}
这是不带空格的同一个 GET 请求:
https://newsapi.org/v1/articles?source=bbc-news&apiKey=c39a26d9c12f48dba2a5c00e35684ecc
- 我正在努力学习 react redux api 调用
- 所以我举了一个例子并在 stackblitz 中实现,但我收到以下错误 GET https://newsapi.org/v1/articles?%20%20%20%20%20%20%20source=bbc-news&apiKey=c39a26d9c12f48dba2a5c00e35684ecc 400(错误请求)
- 你能告诉我怎么解决吗
- 在下面提供我的代码和 stackblitz https://medium.com/@lavitr01051977/basic-react-redux-app-with-async-call-to-api-e478e6e0c48b
https://stackblitz.com/edit/react-redux-realworld-4ldsnt?file=components/ChannelsField.js
export function fetchPosts(channel) {
return function (dispatch) {
dispatch(requestPosts());
return fetch(`https://newsapi.org/v1/articles?
source=${channel}&apiKey=${MY_API_KEY}`)
.then(
response => response.json(),
error => console.log('An error occurred.', error),
)
.then((json) => {
dispatch(receivedPosts(json));
},
);
};
}
看起来您的请求在 ? 之间有额外的空格 (%20)和导致 400 错误请求的来源。将您的函数更改为以下内容,它应该可以工作:
export function fetchPosts(channel) {
return function (dispatch) {
dispatch(requestPosts());
return fetch(`https://newsapi.org/v1/articles?source=${channel}&apiKey=${MY_API_KEY}`)
.then(response => response.json(),
error => console.log('An error occurred.', error),
)
.then((json) => {
dispatch(receivedPosts(json));
},);
};
}
这是不带空格的同一个 GET 请求:
https://newsapi.org/v1/articles?source=bbc-news&apiKey=c39a26d9c12f48dba2a5c00e35684ecc