我正在尝试构建一个使用Spotify API的Web应用程序。我想使用用户输入的输入数据来调用服务器上的Spotify API,并将结果发送回前端。问题是,当我单击“提交”按钮时,页面被重定向到“ http://localhost:4000/search_result”。我该如何预防?
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;
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 }));
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来解决此问题,但那时我无法运行客户端。
答案 0 :(得分:0)
在onSubmit={e => e.preventDefault()}
标记上添加<form>
,然后创建handleClick
函数并使用axios或got npm模块向服务器请求:
<form onSubmit={e => {e.preventDefault();}}>
<button onClick={this.handleClick}>Click</button>
</form>
我完成了main.js,请测试以下代码:
import React, { Component } from "react";
import SingerCard from "./SingerCard";
export class Main extends Component {
constructor(props) {
super(props);
this.state = {
singers: [],
tracks: [],
};
this.formPreventDefault = this.formPreventDefault.bind(this);
}
async componentDidMount() {
const res = await fetch("http://localhost:4000/api/");
const singers = await res.json();
this.setState({ singers });
}
// handler recieves the `e` event object
formPreventDefault(e) {
e.preventDefault();
axios.post('http://localhost:4000/search_result')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
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
onSubmit={this.formPreventDefault}
>
<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;