我刚刚继承了一个项目,该项目是使用我不太熟悉的工具随意构建的。它使用Express,Bookshelf和Axios访问MySQL数据库。 GET和PUT的Express路由似乎工作正常,但是POST和DELETE都导致错误500。

这是我正在使用的路由(我删除了很多运行正常的GET和POST路由):

import express from 'express';
import Points from '../models/points';

let router = express.Router();

// GET all points associated with a specific user AND a specific session
// This works fine.
router.get('/user/:user/session/:session', (req, res) => {
    Points.query({
        select: ['id', 'number', 'quadrant', 'level', 'title', 'category'],
        where: {sessionId: req.params.session, userId: req.params.user}
    }).fetchAll().then(point => {
        res.json({point});
    })
});

// POST a single point to the database.
// This works fine.
router.post('/', (req, res) => {
    const {sessionId, userId, number, quadrant, level, title, category} = req.body;

    Points.forge({
        sessionId, userId, number, quadrant, level, title, category
    }).save()
        .then(user => res.json({success: true}))
        .catch(err => res.status(500).json({error: err}));
});

// PUT (update) an existing point
// Doesn't work right now (500)
router.put('/edit/:identifier', (req, res) => {
    Points.update({
        set: {title: req.params.title},
        where: {id: req.params.identifier}
    }), function (err, point) {
        if (err) {
            return res.send(err);
        }
        res.json({message: 'Updated'});
    };
});

// DELETE a point by id
// Doesn't work right now (500)
router.delete('/delete/:identifier', (req, res) => {
    Points.remove({
        id: req.params.identifier
    }), function (err, point) {
        if (err) {
            return res.send(err);
        } else {
            res.json({message: 'Deleted'});
        }
    };
});

export default router;


以下是与上述路由相对应的Redux操作:

import axios from 'axios';


export function getPointsByUserAndSession(data) {
    return dispatch => {
        return axios.get('/api/points/user/'+data.user+'/session/'+data.session)
    }
}

export function addPoint(data) {
    return dispatch => {
        return axios.post('/api/points', data)
    }
}

export function editPointById(data) {
    return dispatch => {
        return axios.put('/api/points/edit/' + data.id)
    }
}

export function deletePointById(identifier) {
    return dispatch => {
        return axios.delete('/api/points/delete/' + identifier)
    }
}

最佳答案

使用以下代码启用CORS:

 router.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, x-access-token');
  res.header('Access-Control-Allow-Methods', 'GET, POST,OPTIONS, DELETE, PATCH, PUT');
  next();
});

关于javascript - 通过Express,Axios在MySQL PUT和DELETE上出现错误500,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47994009/

10-11 01:27