无法获取 CORS 来允许 POST 方法

问题描述 投票:0回答:1

这里是服务器

const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const cors = require('cors')

const app = express();
const port = 3000;


const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '******',
  database: 'book_store'
});


connection.connect((err) => {
  if (err) throw err;
  console.log('Connected to MySQL database');
});


app.use(cors())
app.options('/users', ( res ) => {
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    res.sendStatus(200);
  });
app.use(bodyParser.json());



app.get('/books', ( res ) => {//get books db
  connection.query('SELECT * FROM books', (err, results) => {
    if (err) throw err;
    const result = res.json(results)
    console.log(result)
  });
});

app.get('/users', ( res ) => {//get users db
    connection.query('SELECT * FROM users', (err, results) => {
      if (err) throw err;
      const result = res.json(results)
      console.log(result)
    });
  });

app.options('/users', cors())

app.post('/users', (req, res) => {
    const { username, email, password, address, role } = req.body;
    console.log('request body', req.body)
    connection.query('INSERT INTO users (username, email, password, address, role) VALUES (?, ?, ?, ?, ?)', 
                     [username, email, password, address, role], 
                     (err, result) => {
      if (err) {
        console.error("Error inserting user:", err);
        res.status(500).json({ error: 'Error inserting user' });
      } else {
        console.log("User inserted successfully");
        res.status(200).json({ success: true });
      }
    })

  });

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

这是前端请求

function addUser(username, email, password, address, role) {
    // Define the data to be sent in the request body
    const userData = {
      username: username,
      email: email,
      password: password,
      address: address,
      role: role
    };

  
    // Make a POST request to the server endpoint
    fetch('/users', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': '*/*'
      },
      body: JSON.stringify(userData) // Convert the data to JSON format
    })
    .then(response => {
      if (!response.ok) {
        throw new Error('Failed to add user');
      }
      return response.json(); // Parse the response JSON
    })
    .then(data => {
      console.log('User added successfully:', data);
      // Handle success if needed
    })
    .catch(error => {
      console.error('Error adding user:', error.message);
      // Handle error if needed
    });
  }


  addUser(username, email, password, address, role)

这是我得到的标题

Request URL:
http://localhost:5500/users
Request Method:
POST
Status Code:
405 Method Not Allowed
Remote Address:
127.0.0.1:5500
Referrer Policy:
strict-origin-when-cross-origin
Access-Control-Allow-Credentials:
true
Access-Control-Allow-Origin:
http://localhost:5500
Allow:
GET, HEAD, OPTIONS
Connection:
keep-alive
Content-Length:
0
Date:
Wed, 24 Apr 2024 23:35:01 GMT
Keep-Alive:
timeout=5
Vary:
Origin
Accept:
*/*
Accept-Encoding:
gzip, deflate, br, zstd
Accept-Language:
es-US,es;q=0.9,es-419;q=0.8,en;q=0.7
Connection:
keep-alive
Content-Length:
91
Content-Type:
application/json
Cookie:
_ga=GA1.1.2077515680.1676588089; _ga_2JPB0HJG8R=GS1.1.1701138391.13.0.1701138391.0.0.0
Host:
localhost:5500
Origin:
http://localhost:5500
Referer:
http://localhost:5500/front/
Sec-Fetch-Dest:
empty
Sec-Fetch-Mode:
cors
Sec-Fetch-Site:
same-origin
User-Agent:
Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1

我不断收到错误 405(方法不允许)。有什么建议吗?

尝试修改cors头,但仍然不起作用。使用邮递员 POST 到服务器似乎工作正常。

javascript node.js json cors
1个回答
0
投票

试试这个:

import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';

const app = express();
const port = 3000;

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

app.post('/users', (req, res) => {
  const { username, email, password, address, role } = req.body;
  console.log('request body', req.body)
  
});

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

我的结果是:

https://i.stack.imgur.com/udtxr.png

不要忘记在代码中将 import 更改为 require

© www.soinside.com 2019 - 2024. All rights reserved.