节点服务器仅接受GET请求,但不会发出POST请求

时间:2020-01-24 15:05:49

标签: javascript node.js reactjs fetch-api body-parser

我能够向本地服务器的/ page路由发出GET请求。但是,从我的客户端提取请求发出POST请求时,什么也没有发生。

这是我的提取请求,数据在数据对象内。我正在尝试显示服务器端。

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: 'no-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>
        )
      }
    }

这是我尝试监听发布请求的节点服务器,那就是我试图拥有数据控制台的地方。

    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(express.static('public'))

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({
       extended: false
    }));

    app.use(passport.initialize())
    passportInit()

    // Accept requests from our client
    app.use(cors({
      origin: CLIENT_ORIGIN
    }))


    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('?')) 

    // Direct other requests to the auth router
    app.use('/', authRouter)

    const handler = (req, res)=> {
      res.setHeader('Content-Type', 'application/json');
      res.send(req.body');
console.log(req.body)
    };

    app.post('/page', handler);



    server.listen(process.env.PORT || 8080, () => { //calllback function
      console.log('listening...')
    })

这是我的package.json文件:

  {
  "name": "social-auth-server",
  "version": "0.0.1",
  "description": "Server for React/Node Social auth",
  "main": "server.js",
  "scripts": {
    "dev": "nodemon server.js",
    "start": "node server"
  },
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.4",
    "dotenv": "^5.0.1",
    "express": "^4.16.3",
    "express-session": "^1.15.6",
    "https": "^1.0.0",
    "multer": "^1.4.2",
    "node-fetch": "^2.6.0",
    "passport": "^0.4.0",
    "passport-facebook": "^2.1.1",
    "passport-github": "^1.1.0",
    "passport-google-oauth": "^1.0.0",
    "passport-twitter": "^1.0.4",
    "path": "^0.12.7",
    "querystring": "^0.2.0",
    "readline": "^1.3.0",
    "request": "^2.88.0",
    "request-promise": "^4.2.2",
    "socket.io": "^2.1.1",
    "stream": "0.0.2"
  },
  "author": "funador",
  "license": "MIT",
  "devDependencies": {
    "nodemon": "^1.19.4"
  }
}

在谷歌浏览器上,我服务器的console.log显示请求方法是GET,我认为它也应该说POST或仅说POST,这就是我认为的问题所在。 console.log image

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('/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

router.use((req, res, next) => {
  req.session.socketId = req.query.socketId
  next()
})

// Routes that are triggered on the client //
router.get('/twitter', twitterAuth)
router.get('/google', googleAuth)
router.get('/facebook', facebookAuth)
router.get('/github', githubAuth)



module.exports = router

0 个答案:

没有答案