向我的本地服务器(localhost:8080 / page)发出发布请求时,系统显示“无法获取/ page”。我enter image description here正在使用Google Chrome浏览器,其中“开发工具”网络标签显示:
这是带有简单fetch语句的前端代码:
import React, { Component } from 'react'
import io from 'socket.io-client'
import OAuth from './OAuth'
import Loading from './Loading'
import Footer from './Footer'
import Tweets from './Tweets'
import { API_URL } from './config'
import './App.css'
const socket = io(API_URL) //,{transports: ['websocket']}
const providers = ['twitter', 'google', 'facebook', 'github']//import theese in because our auth controller needs to call our event for each provider which the event is named after the provider
export default class App extends Component {
state = {
loading: true
}
componentDidMount() {
socket.on('connect', function(){
console.log('connected')
});
fetch(`${API_URL}/wake-up`)
.then(res => {
if (res.ok) {
this.setState({loading: false})
}
})
const data = {
random1: 'random',
random2: 'random-input'
}
const options = {
method:'POST',
mode: 'cors',
header: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}
fetch(`${API_URL}/page`, options);
}
render() {
const divStyles = {
}
const buttons = (providers, socket) =>
providers.map(provider =>
<OAuth
provider={provider}
key={provider}
socket={socket}
/>
)
return (
<div className='wrapper'>
<div className='container'>
{this.state.loading
? <Loading />
: buttons(providers, socket)
}
</div>
{
buttons
? <Tweets provider='twitter' />
: <div> Hasnt fetched</div>
}
<Footer />
</div>
)
}
}
这是我的后端节点服务器(server.js),其中有app.post可用,但仍然没有结果,并且我在下面附加了我的路由文件:
require('dotenv').config()
const express = require('express')
const path = require('path')
const fs = require('fs')
const https = require('https')
const http = require('http')
const passport = require('passport')
const session = require('express-session')
const cors = require('cors')
const socketio = require('socket.io')
const authRouter = require('./lib/auth.router')
const passportInit = require('./lib/passport.init')
const { SESSION_SECRET, CLIENT_ORIGIN } = require('./config')
const bodyParser = require('body-parser')
const app = express()
let server
// If we are in production we are already running in https
if (process.env.NODE_ENV === 'production') {
server = http.createServer(app)
}
// We are not in production so load up our certificates to be able to
// run the server in https mode locally
else {
const certOptions = {
key: fs.readFileSync(path.resolve('./certs/server.key')),
cert: fs.readFileSync(path.resolve('./certs/server.crt'))
}
server = https.createServer(certOptions, app)
}
// Setup for passport and to accept JSON objects
app.use(express.json())
app.use(bodyParser.json());
app.use(passport.initialize())
passportInit()
// Accept requests from our client
app.use(cors())
// saveUninitialized: true allows us to attach the socket id to the session
// before we have athenticated the user
app.use(session({
secret: process.env.SESSION_SECRET,
resave: true,
saveUninitialized: true
}))
// Connecting sockets to the server and adding them to the request
// so that we can access them later in the controller
const io = socketio(server)
app.set('io', io)
// Catch a start up request so that a sleepy Heroku instance can
// be responsive as soon as possible
app.get('/wake-up', (req, res) => res.send('?'))
app.post('/page', (req, res)=>{
res.setHeader('Content-Type', 'application/json');
res.send('yes');
})
// Direct other requests to the auth router
app.use('/', authRouter)
server.listen(process.env.PORT || 8080, () => { //calllback function
console.log('listening...')
})
路由文件auth.router.js:
const express = require('express')
const router = express.Router()
const passport = require('passport')
const authController = require('./auth.controller')
// Setting up the passport middleware for each of the OAuth providers
const twitterAuth = passport.authenticate('twitter')
const googleAuth = passport.authenticate('google', { scope: ['profile'] })
const facebookAuth = passport.authenticate('facebook')
const githubAuth = passport.authenticate('github')
// Routes that are triggered by the callbacks from each OAuth provider once
// the user has authenticated successfully
router.get('/twitter/callback', twitterAuth, authController.twitter)//on callback we are authenticating twitter and then sending our data/user info to the io to be called up on client via the socket.io (socket.on())
router.get('/google/callback', googleAuth, authController.google)
router.get('/facebook/callback', facebookAuth, authController.facebook)
router.get('/github/callback', githubAuth, authController.github)
// This custom middleware allows us to attach the socket id to the session
// With that socket id we can send back the right user info to the right
// socket
router.use((req, res, next) => {
req.session.socketId = req.query.socketId
next()
})
// Routes that are triggered on the client ////so may not need certain code from the twitter developer page
router.get('/twitter', twitterAuth)
router.get('/google', googleAuth)
router.get('/facebook', facebookAuth)
router.get('/github', githubAuth)
module.exports = router
答案 0 :(得分:0)
如果您想同时使用两个动词,则需要为get和post定义路线。您可以执行以下操作:
const handler = (req, res)=> {
res.setHeader('Content-Type', 'application/json');
res.send('yes');
};
app.get('/page', handler);
app.post('/page', handler);