有没有一种方法可以防止表单提交后重定向,并且仍将表单数据发送到服务器?

I'm trying to build a web app which uses Spotify API. I wanna use the input data that a user enters to call Spotify API on the server and send the result back to the front end. The problem is the page is redirected to 'http://localhost:4000/search_result' when I click the submit button. How do I prevent this?

main.js

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

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

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

  render() {
    return (
      <div className="main">
        <div className="genres">
          <h2 className="header text-capitalize">
            top 10 tracks of famous singers
          </h2>
        </div>
        <div className="container">
          {this.state.singers.map((elem) => (
            <SingerCard
              image={elem.images}
              name={elem.name}
              tracks={this.state.tracks}
            />
          ))}
        </div>
        <br />
        <form
          action="http://localhost:4000/search_result"
          method="POST"
        >
          <label htmlFor="search">Search an artist: </label>
          <span>
            <input type="search" id="search" name="search" />
            <button type="submit">Search</button>
          </span>
        </form>
      </div>
    );
  }
}

export default Main;

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

app.post("/search_result", (req, res) => {
  console.log(req.body);
  res.send("The artist you are searching for" + req.body.search + ".");
  res.end();
});

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

我试图通过将服务器端口设置为3000来解决此问题,但是那时我无法运行客户端。

评论