如何将POST请求中的数据用于下一个GET请求

时间:2020-05-20 04:29:33

标签: node.js reactjs express axios

我正在尝试构建一个使用Spotify API的Web应用程序。我希望它发送用户提交给服务器的搜索关键字,并将其搜索结果发送回前端。问题是我为提取调用获得了404状态代码。 POST请求工作正常。

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",
            "Access-Control-Allow-Origin": "*",
          },
        }
      )
      .then(function (res) {
        console.log(res);
      })
      .catch(function (err) {
        console.log(err);
      });
  }

  componentDidMount() {
    fetch("http://localhost:4000/api")
      .then((res) => res.json)
      .then((artists) => {
        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="container">
           {this.state.artists.map((elem) => (
            <SingerCard
              images={elem.images}
              name={elem.name}
              artists={this.state.artists}
            />
          ))} 
          {console.log(this.state.artists)}
        </div>
        <br />
      </div>
    );
  }
}

export default Main;

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 }));

// Create the api object with the credentials
var spotifyApi = new SpotifyWebApi({
  clientId: process.env.CLIENT_ID,
  clientSecret: process.env.CLIENT_SECRET,
});

// Retrieve an access token.
spotifyApi.clientCredentialsGrant().then(
  function (data) {
    console.log("The access token expires in " + data.body["expires_in"]);
    console.log("The access token is " + data.body["access_token"]);

    // Save the access token so that it's used in future calls
    spotifyApi.setAccessToken(data.body["access_token"]);
  },
  function (err) {
    console.log("Something went wrong when retrieving an access token", err);
  }
);

app.post("/search_result", (req, res) => {
  console.log(req.body.keyword);
  spotifyApi.searchArtists(req.body.keyword).then(function (data) {
    var search_res = data.body.artists.items;
    res.json(search_res);

    app.get("http://localhost:/api", (req, res) => {
      res.json(search_res);
      res.end();
    });

    res.end();
  }),
    function (err) {
      console.log(err);
    };
});

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

我认为app.post()中的app.get()会导致错误,但我想不出另一种方法将搜索结果发送回去。

2 个答案:

答案 0 :(得分:0)

由于get方法的定义不正确,您得到了404。

更新服务器代码以定义get方法以仅保留路径名,如下所示:

 app.get("/api", (req, res) => {
   // ...
 }

当前,您正在app.post中定义此路由。 get路由定义应位于post路由之外。

答案 1 :(得分:0)

使用Axios.get

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();
    const headers = {
      "Content-Type": "application/json",
      "Access-Control-Allow-Origin": "*"
    };
    axios.post(
        "https://jsonplaceholder.typicode.com/users",
        { keyword: this.state.keyword },
        { headers: headers }
      )
      .then(res => {
        console.log(res.data);
      })
      .catch(err => {
        console.log(err);
      });
  }

  componentDidMount() {
    axios.get("https://jsonplaceholder.typicode.com/users").then(res => {
      this.setState({
        artists: res.data
      });
    });
  }

  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="container">
          {this.state.artists.map(elem => (
            <div key={elem.id}>
              <ul>
                <li>{elem.name}</li>
              </ul>
            </div>
          ))}
        </div>
      </div>
    );
  }
}

export default Main;
相关问题