當我從React前端發送請求時,我在Chrome、Firefox和Postman的網路標簽上測驗了Axios給出的回應型別,結果顯示在localhost上顯示為application/json型別,而在Heroku的生產中則為text/html型別。我設定的路由是回傳res.json(),所以我不確定是什么原因導致了這個問題。
index.js
const express = require("express") 。
const dotenv = require("dotenv") 。
const path = require('path')。
//加載env。
dotenv.config({ path: './config.env' })。)
const app = express();
app.use(express.json()。
// Routes
app.use('/', require('./routes/routes')) 。
const port = process.env.PORT || 8080;
if(process.env.NODE_ENV == 'production')
{
app.use(express.static(path.join(__dirname, 'build'))。
app.get('/*', (req, res) => /span> {
res.sendFile(path.join(__dirname, 'build', 'index.html') )。)
});
}
app.listen(port, () => {
console.log(`Listening at port ${port}`) 。
});
routes.js
const express = require("express") 。
const router = express.Router();
const mysql = require('mysql2')。
const db = mysql.createPool.
({
user: `${process.env.USER}`。
host: `${process.env.HOST}`。
password。`${process.env.PASSWORD}`。
database: `${process.env.DATABASE}`。
connectionLimit: 10,
waitForConnections: true。
});
router.get('/user', (req, res) =>/span>
{
try
{
let id = req.query.id。
let admin = 0;
//檢查資料庫,看是否有一個與給我們的ID相同的用戶。。
//如果沒有,創建一個新用戶。
db.query("SELECT * FROM users WHERE id = ?", [id], (err, result) => //span>
{
if(result.length == 0)
{
db.query("INSERT INTO users (id, admin) VALUES (?, ?)" , [id, admin]) 。
}
return res.status(200).json({"result"_span>: result}) 。
});
}
catch (err)
{
console.log(err)。
return res.status(400).json({error。"用戶發生錯誤"})。)
}
});
router.post('/addMatch', (req, res) =>/span>
{
try
{
let uid = req.body.uid。
let mid = req.body.mid。
db.query("INSERT INTO matches (uid, mid) VALUES (?, ?)", [uid, mid], (err, result) =>
{
return res.status(200).json({"result"_span>: result}) 。
});
}
catch (err)
{
console.log(err)。
return res.status(400).json({error。"addMatch發生錯誤"})。)
}
});
router.post('/deleteMatch', (req, res) =>/span>
{
try
{
let uid = req.body.uid。
let mid = req.body.mid。
db.query("DELETE FROM matches WHERE uid = ? AND mid = ?", [uid, mid], (err, result) =>
{
return res.status(200).json(result)。
});
}
catch (err)
{
console.log(err)。
return res.status(400).json({error。"deleteMatch發生錯誤"})。)
}
});
router.get('/getMatches', (req, res) =>/span>
{
try
{
let id = req.query.id。
db.query("SELECT * FROM media WHERE id IN (SELECT mid FROM matches WHERE uid = ?);", [id], (err, matches) => //span>
{
return res.status(200).json(matches)。
});
}
catch (err)
{
console.log(err)。
return res.status(400).json({error。"getMatches發生錯誤"})。)
}
});
router.get('/getMovie', (req, res) =>/span>
{
try
{
let id = Math.floor(Math. random() * 50) 1;
db. query(`SELECT * FROM media WHERE id = ${id}`, (err, result) => //span>
{
return res.status(200).json(result[0] )。)
});
}
catch (err)
{
console.log(err)。
return res.status(400).json({error。"getMovie發生錯誤"})。)
}
});
module.exports = router;
Swipe.js
import React from "reaction";
import MatchResults from "./components/MatchResults"。
import Data from ' ./components/Data';
import { Container, Button } from 'reactstrap'/span>;
import { withAuth0 } from "@auth0/auth0-react" 。
import axios from 'axios'/span>;
import './styles/Swipe.css';
class Swipe extends React.Component
{
constructor(props)
{
super(props)。
const { user } = this.props.auth0;
this.state = {
data: {},
uid: user.sub.split('|')[1] 。
matches: []
};
this.yesButtonApi = this。 yesButtonApi.bind(this)。
this.noButtonApi = this。 noButtonApi.bind(this)。
this.getMovie = this。 getMovie.bind(this)。
this.getMatches = this。 getMatches.bind(this)。
}
componentDidMount()
{
this.getMovie()。
this.getMatches()。
}
yesButtonApi()
{
try
{
var body = {
uid: this.state.uid。
mid: this.state.data.id。
}
axios.post('/addMatch', body).then(( ) =>)
{
this.getMovie()。
this.getMatches()。
});
}
catch (error)
{
console.log(錯誤)。
}
}
noButtonApi()
{
try
{
this.getMovie()。
}
catch (error)
{
console.log(錯誤)。
}
}
getMovie()
{
try
{
axios.get('/getMovie').then((response) => //span>
{
this.setState.
({
data: response.data.
});
});
}
catch (error)
{
console.log(錯誤)。
}
}
getMatches()
{
try
{
let uid = this.state.uid。
axios.get(`/getMatches?id=${uid}`/span>)。 then((response) =>
{
this.setState.
({
matches: response.data.
});
});
}
catch (error)
{
console.log(錯誤)。
}
}
render()
{
return (
<div className="text-center"/span>>
<Container className="swipe">/span>
<Data title={this.state.data.title} description={this. state.data.description} rating={this.state.data.rating} preview={this.state.data.video}/>
<Button color="success" onClick={this. yesButtonApi} className="ml-sm">Yes</Button>
<Button color="danger" onClick={this. noButtonApi} className="ml-sm">No</Button>/span>
<MatchResults matches={this. state.matches} uid={this.state.uid}/>
</Container>
</div>
)
}
}
export default withAuth0(Swipe)。
MatchResults.js
import React, { Component } from 'react;
import { Card, CardBody, Container, CardHeader, Row, Col, Collapse, Button } from 'reactstrap'/span>;
import { AiFillStar } from 'react-icons/ai'/span>;
import './styles/MatchResults.css';
import axios from 'axios'/span>;
class MatchResults extends Component
{
constructor(props)
{
super(props)。
this.state = { isOpen: false, matches: this.props.matches, uid。this.props.uid }。
this.toggle = this。 toggle.bind(this)。
this.getMatches = this。 getMatches.bind(this)。
this.deleteButtonApi = this。 deleteButtonApi.bind(this)。
}
componentDidUpdate(prevProps)
{
if(this.props !== prevProps)
{
this.setState !
({
matches: this.props.matches。
});
}
}
toggle()
{
try
{
this.setState.
({
isOpen: !this.state.isOpen.
});
if(this.state.isOpen)
{
this.getMatches()。
}
}
catch (error)
{
console.log(錯誤)。
}
}
getMatches()
{
try
{
let uid = this.state.uid。
axios.get(`/getMatches?id=${uid}`/span>)。 then((response) =>
{
this.setState.
({
matches: response.data.
});
});
}
catch (error)
{
console.log(錯誤)。
}
}
deleteButtonApi(e)
{
try(e)
{
var body = {
uid: this.state.uid。
mid: e.target.value.
}
axios.post('/deleteMatch', body).then(( ) =>)
{
this.getMatches()。
});
}
catch (error)
{
console.log(錯誤)。
}
}
render()
{
return (
<Container className="match-results"/span>>
<div className="text-center"/span>>
<Button color="primary" onClick={this. toggle} style={{ marginBottom: '1rem' }}>View Matches</Button>
<Collapse isOpen={this.state.isOpen}>/span>
<Row>/span>
{
this.state.matches.map((item, val) =>
{
val = 1;
回傳 (
< Col sm="12" md="6"/span> lg="4"/span>>
< Card key={val} className="match-results-card" data-testid="card">
<CardHeader>/span>
<div data-testid="title"/span>>
{item.title}
</div> {item.title}
<span data-testid="rating">
<AiFillStar />>
{專案.評級}
</span> {item.rating}
</CardHeader>/span>
<CardBody>/span>
<div data-testid="description"/span>>
{item.description}
</div>{item.description}。
</CardBody>/span>
< 按鈕 className="deleteBtn"/span> color="danger" onClick={this. deleteButtonApi} value={item.id}>Delete</Button>/span>
</Card>/span>
</Col>
)
})
}
</Row> ) } </Row>
</Collapse>/span>
</div>
</Container>/span>
)
}
}
export default MatchResults;
Localhost
生產
你在生產部署中得到的回應是默認的index.html,當你的節點服務器配置出現問題時,就會送達。這不是關于回應是text/html的問題,而是關于節點服務器的設定不正確(可能沒有一個路由在作業)。基本問題可能是任何問題,在這個問題中有幾個例子。
我建議首先查看您的生產環境中的 node.js 日志(除錯 Heroku 上的 Node.js 應用程式)
。轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/319756.html
標籤:




