角POST请求已被CORS策略阻止:对预检请求的响应未通过访问控制检查

时间:2019-09-23 07:41:23

标签: javascript node.js angular cors

我已经在后端设置了cors,我只是不知道为什么当URL正确时我会收到404错误。错误是CORS策略已阻止从源“ http://localhost:3008/api/vehicle”访问“ http://localhost:3007”处的XMLHttpRequest:对预检请求的响应未通过访问控制检查:它没有HTTP正常状态。我还在下面添加了我的api跨域。请检查下面的示例代码。该问题的解决方案是什么?是什么原因导致此问题?我已经在后端设置了cors,我只是不知道为什么当URL正确时我会收到404错误。错误是CORS策略已阻止从源“ http://localhost:3008/api/vehicle”访问“ http://localhost:3007”处的XMLHttpRequest:对预检请求的响应未通过访问控制检查:它没有HTTP正常状态。我还在下面添加了我的api跨域。请检查下面的示例代码。该问题的解决方案是什么?是什么原因导致此问题?

有什么主意吗?

Http发布服务

save(vehicle: Vehicle){

    return this.http.post(

        CONSTANST.routes.person.save,
        {
            Stock: vehicle.Stock,
            VIN: vehicle.VIN,
            age: vehicle.age,
            gender: vehicle.gender,
        },                
    );
}

路线

const HOST ='http://localhost:3008'

export const CONSTANST = {
    permissions:{},
    routes:{
        authorization:{
            login: HOST + '/api/app/signin-email',
            logout: HOST + '/api/auth/logout'
        },
        person:{
            list: HOST + '/api/vehicle',
            save: HOST + '/api/vehicle',
        },
        user: {}
    },
    lang:{},
    session:{},
    parameters:{}
};

api跨域请求

if (process.env.NODE_ENV !== 'production') {
    console.log('------------------------------------------------');
    console.log('Notice: Enabling CORS for development.');
    console.log('------------------------------------------------');
    app.all('*', function (req, res, next) {
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Methods', 'GET, POST');
        res.header('Access-Control-Allow-Headers', 'Content-Type');
        next();
    });
}

api路线

app.get('/api/vehicle',  keystone.middleware.api, routes.api.vehicle.list);
    app.post('/api/vehicle',  keystone.middleware.api ,routes.api.vehicle.create);

2 个答案:

答案 0 :(得分:0)

在您的情况下,URL可能是正确的,但是您在api路由中没有为“ OPTIONS”请求方法配置的处理程序。应该像对GET或POST请求一样进行配置。这样一来,您在收到预检请求后就会收到404响应。

app.options('/api/vehicle',  keystone.middleware.api ,routes.api.vehicle.create);

但是您不需要通过逻辑传递回调,因为您将执行两次逻辑。

此外,我可以建议您为所有路线做一个选项处理程序:

app.options('*', someSimpleCallback);

答案 1 :(得分:0)

在我的情况下,我想删除的对象ID后面缺少斜杠。

如果您将Django Rest Framework用于后端,请确保已设置ALLOWED_HOSTS。您可能还需要使用django-cors-headers应用。