Send Ajax POST to another port?

Asked

Viewed 66 times

0

I am making a website with pure PHP/JS, but I need to use the services of Google Calendar API and wanted to use them with Node. My Node server is running on port 3333 and PHP on 80. I tried to use AJAX to send a POST request to my NODE backend but it is not working.

Here is my AJAX code:

$.ajax({
    url: 'localhost:3333',
    method: 'POST',
    data:{
        name: "Joao",
        idade: 25,
        peso: 30
    }, success: function(data){
        alert(data);
    }, error: function(data){
    console.log(data);
    }
});

Chrome console returns me "Access to Xmlhttprequest at 'localhost:3333/api' from origin 'http://127.0.0.1:70' has been blocked by CORS policy". I searched and saw that it is a policy of cross-Omain but I do not know how to make it work since I can not use a different port in AJAX.

My Node project index.js:

const express = require("express");
const routes = require("./routes");
const cors = require('cors');


const app = express();

app.use(cors());
app.use(express.json());
app.use(routes);



app.listen(3333);

My file Routes.js:

const express = require("express");
const routes = express.Router();


routes.post('/', (request, response) => {
    const body = request.body;
    console.log(body);
    return response.send('Request received');
});

module.exports = routes;

How do I send a post from my website to this port?

1 answer

1

Hello,

To fix this CORS problem that is coming from your server, you can use the library cors, just follow these steps:

  • npm install -s cors

Now in your code node, you will import it. So:

const cors = require('cors');

Now, if you’re using express, do the following:

app.use(cors())

You need to put this code on top of all the others app.use(...) so that it has an effect on the next.

  • Hello, friend! Thank you for your answer and for the type of application I usually develop I’m sure your tip will be very useful in the future! Anyway it didn’t work at the time, I think the problem is in the PHP/JS/AJAX page itself that sends the request pro server, so I think the server should not be the problem. I did a search and it’s usually the browser that blocks...

  • Hello @Marcosoliveira :) So you can show me what you did in Node code?

  • Sure! I edited the question and added the Node server codes.

  • Are you using nodemon? If not, have you updated Node? (Turn off and turn on again with the new changes)

  • I am using nodemon yes, friend. I have also tried to close and give npm start dnv and nothing...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.