gpt4 book ai didi

javascript - 如何使用 XMLHttpRequest 对象发出 post 请求?

转载 作者:行者123 更新时间:2023-11-29 17:01:14 25 4
gpt4 key购买 nike

我在客户端有一个 JavaScript 片段,通过跨域从另一个 Rails API 应用程序请求数据。

var myData = { "event": {"name": "some event name", "property": "some value"} };
var request = new XMLHttpRequest();
request.open("POST", "http://localhost:3000/api/events", true);
request.setRequestHeader('Content-Type', 'application/json');
request.send(JSON.stringify(myData));

我想知道为什么添加 request.setRequestHeader('Content-Type', 'application/json'); 会导致浏览器发送一个 POST 请求,但没有这个声明, 浏览器发送 OPTIONS 请求

此外,运行上述代码时,我的 Rails 应用程序中出现错误 ActionController::ParameterMissing - param is missing or the value is empty: event:。为什么浏览器不发送myData变量中的数据集?

版本信息:ruby 2.1.5p273,Rails 4.1.8

# routes.rb

Rails.application.routes.draw do
match '/api/events' => 'api/v1/events#create', via: :options
...
end

# app/controller/api/v1/events_controller.rb

class API::V1::EventsController < ApplicationController
skip_before_action :verify_authenticity_token
before_action :set_headers

def index
@events = Event.all
render json: @events, status: :ok
end

def show
@event = Event.find(params[:id])
render json: @event
end

def create
@event = Event.new(event_params)
if @event.save
render json: @event, status: :created
else
render @event.errors, status: :unprocessable_entity
end
end

def update
@event = Event.find(params[:id])
if @event.update(event_params)
raise "#{@event.name}"
head :no_content
else
render @event.errors, status: :unprocessable_entity
end
end

private

def event_params
params.require(:event).permit(:name, :property)
end

def set_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Expose-Headers'] = 'ETag'
headers['Access-Control-Allow-Methods'] = 'OPTIONS' #'GET, POST, PATCH, PUT, DELETE, OPTIONS, HEAD'
headers['Access-Control-Allow-Headers'] = '*,x-requested-with,Content-Type,If-Modified-Since,If-None-Match'
headers['Access-Control-Max-Age'] = '1728000'
end
end

# Rails log

Started OPTIONS "/api/events" for 127.0.0.1 at 2015-01-09 14:54:31 -0600
Processing by API::V1::EventsController#create as */*
Completed 400 Bad Request in 2ms

ActionController::ParameterMissing - param is missing or the value is empty: event:
actionpack (4.1.8) lib/action_controller/metal/strong_parameters.rb:187:in `require'
app/controllers/api/v1/events_controller.rb:39:in `event_params'
app/controllers/api/v1/events_controller.rb:18:in `create'
actionpack (4.1.8) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
...

最佳答案

浏览器为每个跨域 ajax post 请求发送 OPTIONS 请求以检查请求是否安全。要了解更多信息,请搜索“cors”。

要解决您的问题,请从 Controller 中删除“set_header”before_filter

  1. 将 gem 'rack-cors' 添加到 Gemfile
  2. 捆绑安装
  3. 将以下内容添加到 config/application.rb
config.middleware.insert_before 0, "Rack::Cors" do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options, :put, :head, :delete]
end
end

关于javascript - 如何使用 XMLHttpRequest 对象发出 post 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27869341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com