繁体   English   中英

无法从前端客户端向本地节点服务器发出 fetch post 请求,只有 GET 请求有效

[英]Cant make a fetch post request from front end client to local node server, only GET requests work

当向我的本地服务器 (localhost:8080/page) 发出 post 请求时,我显示“无法获取 /page”。 我在这里使用谷歌浏览器输入图像描述,其中开发工具网络选项卡显示:

这是我的前端代码,带有简单的 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

如果您希望能够使用这两个动词到达它,您需要为 get 和 post 定义您的路线。 你可以这样做:

const handler = (req, res)=> {
  res.setHeader('Content-Type', 'application/json');
  res.send('yes');
};
app.get('/page', handler);
app.post('/page', handler);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM