如何解决发布请求中的网络错误?

时间:2020-05-19 05:16:52

标签: reactjs express

我正在尝试构建一个Spotify Web应用程序,以根据用户提交的关键字显示艺术家的搜索结果。当我提交搜索关键字时,我的帖子请求正在等待处理,最终在Chrome上失败了。这是我的代码

main.js

import React, { Component } from "react";
import SingerCard from "./SingerCard";
import axios from "axios";

export class Main extends Component {
  constructor(props) {
    super(props);
    this.state = {
      keyword: "",
      artists: [],
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(e) {
    this.setState({ keyword: e.target.value });
  }

  handleSubmit(e) {
    e.preventDefault();
    axios
      .post(
        "http://localhost:4000/search_result",
        {
          keyword: this.state.keyword,
        },
        {
          headers: { "Content-Type": "application/json" },
        }
      )
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
  }

  async componentDidMount() {
    let res = await fetch("http://localhost:4000/api");
    let artists = await res.json();
    this.setState({ artists });
  }

  render() {
    return (
      <div className="main">
        <form onSubmit={this.handleSubmit}>
          <label htmlFor="search">Search an artist: </label>
          <span>
            <input
              type="search"
              value={this.state.keyword}
              onChange={this.handleChange}
              name="keyword"
            />

            <button type="submit" value="Submit">
              Search
            </button>
          </span>
        </form>
        <br />
        <div className="genres">
          <h2 className="header text-capitalize">
            top 10 tracks of famous singers
          </h2>
        </div>
        <div className="container">
          {this.state.artists.map((elem) => (
            <SingerCard
              images={elem.images}
              name={elem.name}
              artists={this.state.artists}
            />
          ))}
        </div>
        <br />
      </div>
    );
  }
}

export default Main;

SingerCard.js

import React, { Component } from "react";
import Modal from "react-bootstrap/Modal";
import notFound from "../../notFound.jpg";

const SingerCard = (props) => {
  const [isOpen, setIsOpen] = React.useState(false);

  const showModal = () => {
    setIsOpen(true);
  };

  const hideModal = () => {
    setIsOpen(false);
  };

  //check if the image array is empty since some artists' image data provided by the API call are empty
  let singer_img = props.images.length === 0 ? notFound : props.images[0].url;

  return (
    <>
      <button type="button" onClick={showModal} style={{ padding: "1px" }}>
        <div className="card" style={{ width: "8rem" }}>
          <img class="card-img-top" src={singer_img} alt="Card image" />
          <div
            className="card-body"
            style={{ height: "4rem", fontSize: "14px" }}
          >
            <p className="card-text">{props.name}</p>
          </div>
        </div>
      </button>
      <Modal show={isOpen} onHide={hideModal}>
        <Modal.Header>
          <Modal.Title>{props.name}'s songs</Modal.Title>
        </Modal.Header>
        <Modal.Body>dc</Modal.Body>

        <Modal.Footer>
          <button type="button" className="btn btn-primary" onClick={hideModal}>
            Close
          </button>
        </Modal.Footer>
      </Modal>
    </>
  );
};

export default SingerCard;

server.js

const express = require("express");
const SpotifyWebApi = require("spotify-web-api-node");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();

const port = 4000 || process.env.PORT;
require("dotenv").config();

app.use(express.json());
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));

// credentials
const spotifyApi = new SpotifyWebApi({
  clientId: process.env.CLIENT_ID,
  clientSecret: process.env.CLIENT_SECRET,
  redirectUri: "http://localhost:8888/callback",
});

app.post("/search_result", (req, res) => {
  console.log(req.body.keyword);

  spotifyApi
    .clientCredentialsGrant()
    .then(function (data) {
      // Set the access token on the API object so that it's used in all future requests
      spotifyApi.setAccessToken(data.body["access_token"]);

      return spotifyApi.searchArtists(req.body.keyword);
    })
    .then(
      function (data) {
        console.log("Artist search result: ", data.body);
        app.get("/api", (req, res) => {
          res.json(data.body.artists.items);
        });
      },
      function (err) {
        console.error(err);
      }
    );
});

app.listen(port, () => console.log(`It's running on port ${port}`));

错误:网络错误 在createError(createError.js:16) 在XMLHttpRequest.handleError(xhr.js:83) 这是Chrome控制台上的错误说明。很抱歉,这个问题很久。

1 个答案:

答案 0 :(得分:0)

首先,在chrome的开发者控制台中,转到“网络”标签,您将在此看到有关该错误的更多详细信息。 在本地主机地址上测试应用程序时,此问题可能是由于CORS引起的。 尝试添加到axios发布请求“ Access-Control-Allow-Origin”:“ *”标头中。

相关问题