api 在 react redux 中调用的 400 错误在示例中工作正常

400 error for api call in react redux working fine in an example

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