我正在学习教程,但在这部分卡住了。多次根据源代码检查我的代码,并在谷歌上搜索了这个错误。有很多结果,但我似乎无法将解决方案应用到我的项目中。
我正在使用 react、express、redis。这里是负责json数据的文件
root dir > react dir > src > App.js
import React from 'react'
import './App.css'
import Jobs from './Jobs'
const JOB_API_URL = 'http://localhost:3000/'
async function fetchJobs(updateCb) {
const res = await fetch(JOB_API_URL)
const json = await res.json()
updateCb(json)
}
function App() {
const [ jobList, updateJobs ] = React.useState([])
React.useEffect(() => {
fetchJobs(updateJobs)
}, [])
return (
<div className="App">
<Jobs jobs={ jobList } />
</div>
);
}
export default App
root dir > worker dir > tasks dir > fetch-github.js
const fetch = require('node-fetch')
const redis = require('redis')
const client = redis.createClient()
const { promisify } = require("util");
const setAsync = promisify(client.set).bind(client);
const baseURL = 'https://jobs.github.com/positions.json'
async function fetchGithub() {
let resultCount = 1
let onPage = 0
let allJobs = []
// fetch all pages
while( resultCount > 0 ) {
const res = await fetch(`${baseURL}?page=${onPage}`)
const jobs = await res.json()
allJobs.push(...jobs)
resultCount = jobs.length
console.log('got', jobs.length, 'jobs')
onPage++
}
console.log('got ' + allJobs.length + ' jobs total' )
// filter algorithm
const jrJobs = allJobs.filter(job => {
const jobTitle = job.title.toLowerCase()
let isJunior = true
// logic
if (jobTitle.includes('senior') || jobTitle.includes('manager') ||
jobTitle.includes('sr.') || jobTitle.includes('architect')) {
return false
}
return true
})
console.log('filtered down to ' + jrJobs.length)
// set in redis
const success = await setAsync('github', JSON.stringify(jrJobs))
console.log({success})
}
module.exports = fetchGithub
根目录 > api 目录 > index.js
const express = require('express')
const app = express()
const port = 3001
const redis = require('redis')
const client = redis.createClient()
const { promisify } = require("util");
const getAsync = promisify(client.get).bind(client);
app.get('/jobs', async (req, res) => {
const jobs = await getAsync('github')
res.header('Access-Control-Allow-Origin', 'http://localhost:3000')
return res.send(jobs)
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})