【问题标题】:How do I use data from POST request for the next GET request如何将 POST 请求中的数据用于下一个 GET 请求
【发布时间】:2020-05-20 14:20:37
【问题描述】:

我现在正在尝试构建一个使用 Spotify API 的网络应用程序。我希望它发送用户提交给服务器的搜索关键字并将其搜索结果发送回前端。问题是我得到一个 404 状态码用于 fetch 调用。 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() 会导致错误,但我想不出另一种方式将搜索结果发回。

【问题讨论】:

  • 我认为您的应用程序中有错字。get app.get("http://localhost:/api" 您缺少端口

标签: node.js reactjs express axios


【解决方案1】:

您收到 404 是因为 get 方法未正确定义。

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

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

目前,您正在app.post 中定义此路由。 get 路由定义应该在post 路由之外。

【讨论】:

  • 我将其更正为“localhost:4000/api”,但仍然得到 404
  • 完全删除localhost:4000,或添加http://。不过最好删除主机名/端口。此外,您应该在app.post 之外定义app.get
【解决方案2】:

使用 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;

【讨论】:

    猜你喜欢
    • 2021-09-05
    • 2014-07-24
    • 2016-03-02
    • 1970-01-01
    • 1970-01-01
    • 2018-04-22
    • 2011-12-16
    • 1970-01-01
    • 2014-05-12
    相关资源
    最近更新 更多