T
T
tj572018-11-28 23:44:52
JavaScript
tj57, 2018-11-28 23:44:52

Why can't I send a POST request with ajax to localhost:3000 (server - node.js)?

There is a form whose data is sent to the server using an AJAX request. The script looks like this:

$(document).ready(function() {

  $("#btn").click(
   function(){
     sendAjaxForm('result_form', 'ajax_form', 'http://127.0.0.1:3000/users');
     return false;
   }
 );

 function sendAjaxForm(result_form, ajax_form, url) {
    $.ajax({
        url:     url,
        type:     "POST",
        dataType: "jsonp",
        data: $("#"+ajax_form).serialize(),
        success: function(response) {
        	result = $.parseJSON(response);
        	$('#result_form').html('Имя: '+result.firstname+'<br>Фамилия: '+result.lastname+'<br>Пол: '+result.sex+'<br>Телефон: '+result.phone+'<br>E-mail:'+result.email+'<br>Дата рождения:'+result.birthdate);
          //console.log("Done");
    	},
    	error: function(response) {
            $('#result_form').html('Ошибка. Данные не отправлены.');
    	}
 	  });

  }

});


CORS error occurs when submitting a form: Access to XMLHttpRequest at ' 127.0.0.1:3000/users ' from origin ' 127.0.0.1:8080 ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.


A field was added to the ajax request: Another error appeared: GET 127.0.0.1:3000/users?callback=jQuery33105526281406... net::ERR_ABORTED 404 (Not Found) There was also an attempt to use a plugin that bypasses CORS blocking: https:/ /chrome.google.com/webstore/detail/allow-co... It was activated and immediately upon refreshing the page, this error began to appear, while it repeats: Access to XMLHttpRequest at '
crossDomain: true,




localhost:8080/sockjs-node/info?t=1543437737940 ' from origin ' 127.0.0.1:8080 ' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

There is also a disconnect message.

How can I solve this problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
shmatuan, 2018-11-28
@shmatuan

CORS needs to be registered on the server

app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET, PUT, PATCH, POST, DELETE");
    res.header("Access-Control-Allow-Headers", "Content-Type");
    next();
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question