我一直在使用javascript库axios尝试向我的Ruby Sinatra / Base API发送POST请求时遇到问题
我在下面的Sinatra API中有一个示例POST路由,axios一直给我一般错误
//This file is mocking a web API by hitting hard coded data.
var authors = require('./authorData').authors;
var _ = require('lodash');
//This would be performed on the server in a real app. Just stubbing in.
var _generateId = function(author) {
return author.firstName.toLowerCase() + '-' + author.lastName.toLowerCase();
};
var _clone = function(item) {
return JSON.parse(JSON.stringify(item)); //return cloned copy so that the item is passed by value instead of by reference
};
var AuthorApi = {
getAllAuthors: function () {
console.log("Inside getAll");
console.log("Authors length is : " + authors.length);
return _clone(authors);
},
getAuthorById: function(id) {
var author = _.find(authors, {id: id});
return _clone(author);
},
saveAuthor: function(author) {
//pretend an ajax call to web api is made here
console.log('Pretend this just saved the author to the DB via AJAX call...');
if (author.id) {
var existingAuthorIndex = _.indexOf(authors, _.find(authors, {id: author.id}));
authors.splice(existingAuthorIndex, 1, author);
} else {
//Just simulating creation here.
//The server would generate ids for new authors in a real app.
//Cloning so copy returned is passed by value rather than by reference.
author.id = _generateId(author);
authors.push(_clone(author));
}
return author;
},
deleteAuthor: function(id) {
console.log('Pretend this just deleted the author from the DB via an AJAX call...');
_.remove(authors, { id: id});
}
};
module.exports = AuthorApi;
使用axios库的我的Javascript代码:
# Running on http://localhost:9292
class Endpoints < Sinatra::Base
register Sinatra::MultiRoute
before do
headers 'Access-Control-Allow-Origin' => 'http://localhost:8080',
'Access-Control-Allow-Methods' => ['OPTIONS', 'GET', 'POST'],
'Access-Control-Allow-Headers' => ['Content-Type']
end
options '*' do
headers 'Access-Control-Allow-Origin' => 'http://localhost:8080',
'Access-Control-Allow-Methods' => ['OPTIONS', 'GET', 'POST'],
'Access-Control-Allow-Headers' => ['Content-Type']
end
route :post, :options, '/create' do
# does something with params and return a JSON object
end
end
我在控制台中不断收到通用的javascript错误
// Running on http://localhost:8080
axios.post('http://localhost:9292/create', {
some_val: 'some value'
})
.then(res => {
console.log(res)
})
.catch(err => {
console.log(err)
})
我的服务器端终端没有给我任何更好的工作,它说选项通过200状态代码传递,但没有给我带来任何导致403错误的东西...没有params使它成功进入我的路线...
POST http://localhost:9292/create 403 (Forbidden) bundle.js:20263
Error: Request failed with status code 403
at createError (bundle.js:12159)
at settle (bundle.js:19627)
at XMLHttpRequest.handleLoad (bundle.js:11996)
答案 0 :(得分:2)
嗯,谢谢,这对我有用:
before do
if request.request_method == 'POST'
body_parameters = request.body.read
begin
data= params.merge!(JSON.parse(body_parameters))
@can_parse = true
rescue
puts "LOG: cant parse params" #TODO add real logger
@can_parse = false
end
end