我有一个像这样的React / Express设置(简化为简洁):
library(tidyverse)
library(lubridate)
scenario <- c("a","a","a","a","a","a","a","a","a","a","a","a","a","a",
"b","b","b","b","b","b","b","b","b","b","b","b","b","b")
str_tstep <- c("2/29/1924", "3/31/1924", "4/30/1924", "5/31/1924", "6/30/1924", "7/31/1924",
"8/31/1924", "9/30/1924", "10/31/1924", "11/30/1924", "12/31/1924", "1/31/1925",
"3/31/1926", "9/30/1926", "1/31/1922", "1/31/1924", "2/29/1924", "5/31/1924",
"10/31/1924","11/30/1924", "12/31/1924", "1/31/1925", "2/28/1925", "1/31/1926",
"2/28/1926", "3/31/1926", "1/31/1927", "1/31/1928")
tstep <- mdy(str_tstep)
value <- c(260,396,348,347,368,397,418,419,190,290,504,323,800,800,355,408,250,365,222,
299,504,323,800,397,288,800,387,415)
df <- data.frame(scenario, tstep, value)
当访问URL const path = require('path')
const express = require('express')
const CLIENT_BUILD_PATH = path.join(__dirname, '../build')
const serialize = data => JSON.stringify({ data })
const app = express()
app.use(express.static(CLIENT_BUILD_PATH))
app.get('/api/get/data', (request, response) => {
Promise.resolve(loadData()).then(data => {
console.log(data)
response.writeHead(200, {'Content-Type': 'application/json'})
response.end(serialize(data))
}).catch((error) => {
response.writeHead(200, {'Content-Type': 'application/json'})
response.end(serialize({}))
})
})
// Catch all route
app.get('*', (request, response) => {
response.sendFile(path.join(CLIENT_BUILD_PATH, 'index.html'))
})
时,我想返回普通的JSON。
E.g。
/api/get/data
但是,返回的是React的 404页。
{
"foo": "bar",
}
解析得很好,我可以在控制台中看到loadData()
。但不知何故,所有路线都会覆盖响应(或其他东西)。我想无论如何,我无法弄清楚。
更新:data
的结构如下:
loadData()
答案 0 :(得分:0)
ExpressJs具有JSON响应的缩写功能。在响应中使用.json()
即可获得所需的结果,例如:
response.json(data);