Post выдает ошибку

I have this code snippet in PHP:

if (strcasecmp($_POST['method'], 'assignId') == 0) {
$username = $_POST['username'];

$response['code'] = 1;
$response['status'] = $api_response_code[$response['code']]['HTTP Response'];
$sql = "CALL new_person('$username')";

if (($result = $conn->query($sql)) === TRUE) {
    $row = $result->fetch_assoc();
    $response['data'] = $row;
}
deliver_response($response);

new_person is a stored procedure which returns an id, it has been tested and works fine and deliver_response returns JSON format of the input. It has also been tested and works fine.

Why do POST Requests return 404 error?

The stored procedure is being executed, but it doesn’t return the result. Finally, when I change the POST method to GET and make a get request instead it works fine!

Rahul's user avatar

Rahul

18.3k7 gold badges41 silver badges60 bronze badges

asked Jan 29, 2016 at 11:15

alfakaiwmega's user avatar

8

404 Error means that the page that has to process the post request can’t be loaded or not exists. You have to check the php and server logs and maybe you can find a answer to your question.

answered Jan 29, 2016 at 11:32

Jorge Gutiérrez Parejo's user avatar

7

Prefix everything, especially your variables. The names you are using are used by WordPress internally (see the comment form), so WordPress might try to do something with your form values. If that fails you get an error.

While $_GET problems are usually rather easy to debug, $_POST and $_REQUEST names are not so simple.

The following list is probably not complete. But its bare length tells us a lesson:

Avoid any name you can find in a dictionary. Prefix your form names.

List of reserved names in $_POST and $_REQUEST used by WordPress 3.5

These names might have side effects when used in themes or plugins. Some are used on specific pages only (removeheader), others on multiple pages or requests. Avoid them all if you can.

_ajax_nonce
_page
_per_page
_signup_form
_total
_url
_wp_http_referer
_wp_original_http_referer
_wp_unfiltered_html_comment
_wpnonce
_wpnonce-custom-header-upload

aa
action
action2
active_post_lock
add_new
add_new_users
addmeta
admin_bar_front
admin_color
admin_email
admin_password
admin_password2
ajax
align
allblogs
allusers
alt
approve_parent
approved
attachment
attachment_id
attachments
auth_cookie
author
author_name
autocomplete_type
auto_draft
auto-add-pages
autosave

background-attachment
background-color
background-position-x
background-repeat
banned_email_domains
blog
blog_name
blog_public
blog_upload_space
blogname
bulk_edit

c
calendar
cat
category_base
category_name
catslist
changeit
changes
charset
checkbox
checked
clear-recent-list
closed
comment
comment_approved
comment_author
comment_author_email
comment_author_url
comment_content
comment_date
comment_ID
comment_parent
comment_post_ID
comment_shortcuts
comment_status
comments_listing
comments_popup
confirmdelete
connection_type
content
context
cpage
create-new-attachment
createuser
customize_messenger_channel
customized
customlink-tab

date
date_format
date_format_custom
day
default-header
delete
delete_all
delete_all2
delete_comments
delete_option
delete_tags
delete_widget
deletebookmarks
deletecomment
deleted
deletemeta
deletepost
description
detached
dismiss
display_name
do

edit_date
email
error
exact
excerpt

features
feed
fetch
fheight
file
fileupload_maxk
filter
find_detached
first_comment
first_comment_author
first_comment_url
first_name
first_page
first_post
found_post_id
fwidth

global_terms_enabled
GLOBALS
gmt_offset
guid

height
hh
hidden
hidden_aa
hidden_jj
hidden_mm
hidden_mn
hidden_hh
history
hostname
hour
html-upload

id
ID
ids
id_base
illegal_names
insert-gallery
insertonlybutton
interim-login
item-object
item-type

jj
json
json_data

key

last_name
limited_email_domains
link_id
link_image
link_name
link_rss
link_url
link_visible
linkcheck
locale
locked
log
logged_in_cookie

m
media
media_type
menu
menu_items
menu-item
menu-item-attr-title
menu-item-classes
menu-item-db-id
menu-item-description
menu-item-object
menu-item-object-id
menu-item-parent-id
menu-item-position
menu-item-target
menu-item-title
menu-item-type
menu-item-url
menu-item-xfn
menu-locations
menu-name
message
meta
metakeyinput
metakeyselect
metavalue
minute
mm
mn
mode
monthnum
more
move
multi_number

name
nav-menu-locations
new
new_role
new_slug
new_title
newcat
newcomment_author
newcomment_author_email
newcomment_author_url
newcontent
newuser
nickname
no_placeholder
noapi
noconfirmation
noredir
number

offset
oitar
option
option_page
order
orderby

p
pb
page
page_columns
page_id
page_options
paged
pagegen_timestamp
pagename
parent_id
pass1
pass2
password
permalink_structure
photo_description
photo_src
phperror
ping_status
plugin
plugin_status
pointer
position
post
post_category
post_data
post_format
post_ID
post_id
post_mime_type
post_password
post_status
post_title
post_type
post_view
postid
posts
preview
primary_blog
private_key
ps
public_key
publish
pwd

query

reassign_user
reauth
redirect
redirect_to
ref
referredby
registration
registrationnotification
rememberme
remove-background
removeheader
removewidget
reset-background
resetheader
review
rich_editing
robots
role

s
same
save
savewidget
savewidgets
screen
scrollto
search
second
section
selectall
selection
send
send_password
sentence
short
show_sticky
sidebar
sidebars
signup_for
signup_form_id
site_id
site_name
sitename
size
skip-cropping
spam
spammed
src
ss
stage
start
static
status
sticky
subdomain_install
submit
subpost
subpost_id
super_admin

tab
tag
tag_ID
tag-name
tag_base
tags_input
tax
tax_input
tag-name
target
taxonomy
tb
term
text-color
the-widget-id
theme
theme_status
thumb
timezone_string
time_format
time_format_custom
title
thumbnail_id
trash
trashed
type

undismiss
unspam
unspammed
untrash
untrashed
url
update_home_url
updated
upgrade
upload_filetypes
upload_space_check_disabled
use_ssl
user
user_id
user_login
user_name
username
users

verify-delete
version
visibility
visible

w
weblog_title
welcome_email
welcome_user_email
widget_id
widget_number
widget-id
widget-recent-comments
widget-rss
width
withcomments
withoutcomments
wp_customize
wp_http_referer
wp_screen_options
wp-preview
WPLANG

x1

y1
year

Variable names

$method // Filter: 'user_contactmethods'
$post_type_name . -tab
$sidebar_id . _position
$taxonomy_name . -tab
$whitelist_options // Filter: 'whitelist_options'

__i__ . $something // used in widgets
new . $taxonomy->name
new . $taxonomy->name . _parent
quick-search-posttype- . $post_type_name
quick-search-taxonomy- . $taxonomy_name
widget- . $id_base

Credit : fuxia

answered May 30, 2019 at 10:32

I am the Most Stupid Person's user avatar

Your code starts with if (strcasecmp($_POST['method'], 'assignId') == 0) {
and the if statement is never closed, so your code runs only on post method

I assume deliver_response throw the 404

answered Jun 4, 2019 at 16:23

Mario's user avatar

MarioMario

3742 silver badges9 bronze badges

  1. Please make sure that you have used the «POST» method in the form of the previous page.
  2. Use the flower brackets properly(you have missed one ending flower bracket for first if condition)

answered Jun 6, 2019 at 6:29

Linith's user avatar

Одной из самых распространенных задач в web-программировании является обработка HTTP-запросов, в частности, GET и POST запросов. Но иногда возникают ситуации, когда веб-приложение не может обработать запросы, которые отправляются на сервер. Это может быть связано с множеством причин, таких как неправильная конфигурация сервера, ошибки в коде приложения или некоторые другие проблемы.

В этой статье мы попытаемся исследовать некоторые из этих причин и предложить пути их решения. Мы также рассмотрим некоторые наиболее часто встречающиеся причины, по которым приложение не может обрабатывать POST/GET запросы.

Проблемы с конфигурацией сервера

Один из наиболее распространенных случаев, когда не удается обработать POST/GET запросы, это проблемы с конфигурацией сервера. Например, некоторые серверы Apache или Nginx могут быть настроены таким образом, что они не позволяют обрабатывать запросы, которые отправляются на сервер. Это может быть связано с различными настройками, такими как доступность определенных портов, использование SSL-сертификатов и др.

Чтобы решить эту проблему, вам может потребоваться изменить настройки вашего сервера. Например, если вы используете сервер Apache, вам может потребоваться настроить файл .htaccess следующим образом:

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/index\.php.*
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

Этот код помогает перенаправлять все запросы на веб-приложение, расположенное в index.php и обрабатывает запросы для отправки их на сервер.

Ошибки в коде приложения

Еще одна частая причина, по которой не удается обработать POST/GET запросы, это ошибки в коде приложения. Наиболее распространенные ошибки, встречающиеся в коде, связаны с неправильным использованием функций и классов, а также типами данных.

Кроме того, некоторые ошибки связаны с неправильным использованием AJAX-запросов, поэтому если вы разрабатываете приложение, которое использует эту технологию, обратите на это больше внимания.

Чтобы исправить ошибки в коде приложения, вам может потребоваться провести отладку кода с использованием инструментов, таких как Xdebug, а также воспользоваться документацией по языкам программирования, фреймворкам или библиотекам, которые вы используете.

Проблемы с передачей данных

Иногда проблема с обработкой POST/GET запросов связана с передачей данных между клиентом и сервером. Например, если данные содержат некорректный формат или не проходят валидацию на стороне сервера, то может произойти ошибка и запрос не будет обработан.

Чтобы решить эту проблему, вам может потребоваться проверить данные, которые отправляются на сервер, а также воспользоваться инструментами для валидации данных, такими как библиотека Laravel.

Неверный URL-адрес

Иногда запрос может быть направлен на неверный URL-адрес, и поэтому сервер не сможет обработать его. Например, если вы используете неправильный URL, то сервер может вернуть ошибку 404.

Чтобы исправить эту проблему, вам может потребоваться проверить URL-адрес запроса и убедиться, что он соответствует ожидаемым параметрам.

В заключение, мы рассмотрели некоторые из наиболее частых причин того, почему не могут обработаться POST/GET запросы. Необходимо помнить, что этот список не является исчерпывающим и проблемы могут возникнуть по многим другим причинам. Однако, если вы понимаете, как работает обработка запросов, то вы сможете диагностировать и исправить большинство проблем.

Из документации:

POST-запросы
При обращении к API-методам типа POST параметры необходимо отправлять в формате application/x-www-form-urlencoded. При этом если в каком-либо из параметров передается вложенная структура , то значения таких параметров необходимо передавать в виде JSON-строки.
Пример передаваемых данных:
site=simple-site&order=%7B%22externalId%22%3A%22a123%22%2C%22firstName%22%3A%22Tom%22%7D

Метод POST /api/v5/loyalty/account/create
Метод проверяет возможность участия клиента в программе лояльности и добавляет его
61968052d3ace720387209.png
Я делаю так:

//Делаем участником бонусов
$url = 'https://mysite.retailcrm.ru/api/v5/loyalty/account/create';
$headers = ['Content-Type: application/x-www-form-urlencoded', 'X-API-KEY: mykey']; // заголовки нашего запроса
$post_data = array(
    'site' => 'mysite',
    'loyaltyAccount' => array('phoneNumber' => $phone, 'cardNumber' => $card, 'customer' => 
          array('externalId' => $response[customers][0][externalId], 'id' => $response[customers][0][id])
                   )
                             );
$data_json = json_encode($post_data); // переводим поля в формат JSON
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_json);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
$result = curl_exec($curl); // результат POST запроса 
////////

print_r($result);покажет если Content-Type: application/json

{«success»:false,»errorMsg»:»Parameter ‘loyaltyAccount[customer]’ is missing»}

или если Content-Type: application/x-www-form-urlencoded’

{«success»:false,»errorMsg»:»Parameter \u0022loyaltyAccount\u0022 is missing»}

print_r($post_data);покажет:

Array
(
    [site] => mysite
    [loyaltyAccount] => Array
        (
            [phoneNumber] => 70000000000
            [cardNumber] => 887895345446
            [customer] => Array
                (
                    [externalId] => bitrix1772073
                    [id] => 31277
                )
        )
)

Почему у меня ошибка

{«success»:false,»errorMsg»:»Parameter \u0022loyaltyAccount\u0022 is missing»}

Что я делаю не так?

I am trying to create a simple form handler using express. I tried the code below for my form:

<form class="form"  action="/" method="post" name="regForm">              
    <div class="form-group">
        <input type="text" name="username" class="form-control" id="username" placeholder="Username">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
</form>

And here is my app.js code:

const port = 3000;

var express = require('express'),
    app = express(),
    server = require('http').createServer(app);
var bodyParser = require('body-parser');

app.use(express.static(__dirname + '/public'));

app.use(bodyParser.urlencoded({
   extended: true;
}));

app.use(bodyParser.json());

app.post('/',function(req,res){
   var username = req.body.username;
   var html = 'Hello:' + username;
   res.send(html);
   console.log(html);
});

server.listen(port);

I keep getting the error «CANNOT POST /» after submitting the form. Am I missing something like a module?

asked Mar 11, 2016 at 2:26

dtem052996's user avatar

1

This way you should try

const port = 3000;

var express = require('express'),
    app = express();
var bodyParser = require('body-parser');

app.use(express.static(__dirname + '/public'));

app.use(bodyParser.urlencoded({
   extended: false
}));

app.use(bodyParser.json());

app.get('/', function(req, res){
  res.render('form');// if jade
  // You should use one of line depending on type of frontend you are with
  res.sendFile(__dirname + '/form.html'); //if html file is root directory
 res.sendFile("index.html"); //if html file is within public directory
});

app.post('/',function(req,res){
   var username = req.body.username;
   var htmlData = 'Hello:' + username;
   res.send(htmlData);
   console.log(htmlData);
});

app.listen(port);

Things you should keep in mind for future Ref :

  1. You were extending url encode to true
  2. You were not having any get request for your form
  3. You were using HTML named variable which is one of bad practices

Dharman's user avatar

Dharman

31.1k25 gold badges86 silver badges137 bronze badges

answered Mar 11, 2016 at 3:53

Amulya Kashyap's user avatar

0

In my case, I wasn’t paying attention to the url I was posting from.

I had the page login http://localhost:5000/login which was posting and, if successful, renders the page account http://localhost:5000/account.

But, playing few times with these 2 pages, the link remained at http://localhost:5000/account but displayed the login page. So, when I was clicking the log in button which had a form with method = "post", I was getting the error Cannot POST /account.

So the fix was to correctly render the login page, by typing in the url of login page http://localhost:5000/login.

answered Jun 13, 2020 at 12:19

Gabriel Arghire's user avatar

Gabriel ArghireGabriel Arghire

2,0421 gold badge21 silver badges34 bronze badges

Another Way is that we can use .route method provided by express

https://expressjs.com/en/guide/routing.html

Eg:

app.route("url")
   .get(function())

   .post(function());

remember to close the .route function using semi colon ;

answered May 14, 2020 at 13:27

Samarth's user avatar

1

Seems to work fine here.

The only bug I found is here:

extended: true;

You need to remove the semicolon at the end.

Also, you don’t need action=»/» in your form tag, just FYI.

answered Mar 11, 2016 at 2:41

chmod's user avatar

chmodchmod

646 bronze badges

2

Check for any trailing whitespace in your path strings. Sounds super simple but it took me two days to figure this was even possible. It seems that if your paths look like this

router.post('/foo ', (req, res)=> { // I hope you see it!
    res
        .status(200)
        .send({msg: 'Foo!'})
})

Instead of this

router.post('/foo', (req, res)=> {
    res
        .status(200)
        .send({msg: 'Foo!'})
})

You will get the «Cannot METHOD /PATH» error. It just so happens the browser is nice enough to truncate the trailing whitespace in it’s error message as to not inconvinience you with unecessary information.

Stay safe kids, use «highlight whitespaces» in your editors for your own sanity.

answered Jul 17, 2022 at 16:38

Bar Akiva's user avatar

Bar AkivaBar Akiva

1,0991 gold badge12 silver badges23 bronze badges

You should call router instead of app
const router = express.Router();

router.use(bodyParser.urlencoded({ extended: false }));

router.post('/',function(req,res){
   var username = req.body.username;
   var htmlData = 'Hello:' + username;
   res.send(htmlData);
   console.log(htmlData);
});

answered Feb 5, 2021 at 11:11

ImranShaik's user avatar

ImranShaikImranShaik

331 silver badge9 bronze badges

Check if you have done one of the following:

  1. You probably have a repeating .post activity with the same name
  2. You probably have a repeating API in other modules with the same name
  3. The API is not registered in your server.js
  4. You may have entered a wrong name while calling from the controllers…

answered Sep 1 at 12:53

Suprabhat Mohapatra's user avatar

Я пытаюсь сделать запрос Ajax для запуска php файла на локальном http-сервере. Я получаю Error 405: method not allowed в консоли браузера.

Я пробовал ответы на некоторые подобные вопросы безрезультатно. Я использую HTTP-сервер npm для его размещения. Я попытался включить CORS на http-сервере, который не решает проблему.

Я могу сузить свою проблему до следующего кода (используя ответ здесь).

/test.html:

<html>
    <head>
        <title>Button</title>
        <meta charset="utf-8">
        <!-- jQuery -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>  
    </head>
    <body>
        <button type="button">Click Me</button>
        <p></p>
        <script type="text/javascript">
            $(document).ready(function(){
                $("button").click(function(){
                    $.ajax({
                        method: 'POST',
                        url: 'echo.php',
                        success: function(data) {
                            alert(data);
                            $("p").text(data);

                        }
                    });
                });
            });
        </script>
    </body>
</html>

/echo.php:

<?php
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type, Accept');
    echo "HELLO WORLD";
?>

Я запускаю сервер, используя http-server от npm. Когда я пытаюсь выполнить POST-запросы (т.е. Нажмите кнопку), я получаю следующую ошибку в журнале сервера:

[...] "POST /echo.php" Error (404): "Not found"

Файл echo.php определенно существует — я могу сделать запросы GET на тот же URL-адрес. Я также вижу следующую ошибку в моей консоли браузера:

POST http://127.0.0.1:8080/echo.php 405 (Method Not Allowed)
    send @ jquery.min.js:4
    ajax @ jquery.min.js:4
    (anonymous function) @ test.html:15
    dispatch @ jquery.min.js:3
    q.handle @ jquery.min.js:3

Когда я делаю запрос GET, ошибок не возникает, и код echo.php помещается внутри <p>, как и следовало ожидать.

Это проблема с конфигурацией моего сервера или просто с проблемой кода?

Обновление 1:

Не так много информации, которую я могу получить из http-сервера. Вот полный журнал, включая команду выполнения:

$ http-server --cors -p 8080

Starting up http-server, serving ./
Available on:
  http://127.0.0.1:8080
Hit CTRL-C to stop the server
[Sat Sep 24 2016 16:47:14 GMT-0400 (EDT)] "GET /test.html" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.101 Safari/537.36"
[Sat Sep 24 2016 16:47:19 GMT-0400 (EDT)] "POST /echo.php" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.101 Safari/537.36"
[Sat Sep 24 2016 16:47:19 GMT-0400 (EDT)] "POST /echo.php" Error (404): "Not found"

Обновление 2

http-server не поддерживает запросы POST в конце концов. См. Ниже ответ…

Понравилась статья? Поделить с друзьями:
  • Post removal возвратил код ошибки 1
  • Post installation возвратил код ошибки 134
  • Post installation возвратил код ошибки 127
  • Polaris pmc 0517ad ошибка e2
  • Polaris pmc 0516adg ошибка e2