我将我的应用程序部署到了Heroku,并且在server.js上定义了一个端点:
const express = require('express');
const path = require('path');
const app = express();
const csv = require('csvtojson');
const geocode = require('./geocode.js')
app.use(express.json())
app.use(express.static(path.join(__dirname, '..', 'build')));
const PORT = process.env.PORT || 5000
app.get('/city', async (req, res) => {
if (!req.query.address) {
return res.status(400).send()
}
try {
const data = await csv().fromFile('./assets/cities_csv.csv')
const city = data.find((city) => city['Hebrew name'].replace("-", ' ') === req.query.address.replace("-", ' '))
if (!city) {
return res.status(404).send()
}
geocode(city['English name'].replace("-", " ") + ", Israel", (error, body) => {
if (error) {
return res.status(500).send(error)
}
body.population = city.Population
body.hebrewName = city['Hebrew name']
res.send(body)
})
} catch (e) {
res.status(500).send(e)
}
})
app.listen(PORT, () => {
console.log(`server started on port ${PORT}`)
});
我这样称呼这个端点(我在前端使用react):
const [form] = Form.useForm();
const { addToData, data } = props
const globalHeaders = {
pragma: 'no-cache',
'cache-control': 'no-cache',
'Content-Type': 'application/json',
};
const submitCity = async ({ cityname }) => {
if (!data.find((city) => city.hebrewName === cityname.replace("-", ' '))) {
try {
const response = await fetch('/city?address='+encodeURIComponent(cityname), {
method: 'GET',
headers : globalHeaders
})
if (response.status === 200) {
const body = await response.json()
addToData(body)
form.resetFields();
return;
}
} catch (e) {
console.log(e)
}
}
animateCSS('.inputbar', 'shakeX').catch((e) => {
console.log(e)
}).then(() => form.resetFields());
}
这在本地运行良好,但是当我将其部署到heroku时,每当我向https://APPNAME.herokuapp.com/city?address=test发送请求时,我只会得到index.html页面,而不是我要查找的JSON。这将导致此错误:“ SyntaxError:JSON中位置0的意外令牌<”。
谢谢!