MySQL PUT上的错误500和通过Express,Axios删除

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

我刚刚继承了一个项目,该项目使用我不太熟悉的工具有点随意构建。它使用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)
    }
}
javascript mysql express redux axios
1个回答
0
投票

使用以下代码启用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();
});
© www.soinside.com 2019 - 2024. All rights reserved.