Search code examples
jqueryexpressxmlhttprequest

JS How to send http get request to my express server?


I'm trying to send a http get request to my simple server written with js express the problem is that i dont know what should i put in url to connect to my server which will run local.
Second question how can i get value from the get request? in this example "something" value send in request

server

const express = require('express');
const app = express();
const PORT = 4001;
app.get("/question",(req, res, next) => {
    res.send("something")
    console.log("got something")
})
app.listen(PORT, () =>{
    console.log("working")
})

client

$(document).ready(function () {
    $('.item').on('click', (element) =>{
        $.get(??????/question)
    })
})

Solution

  • Since the client is not a part of the express app and assuming you have run dev mode.

    http://localhost:4001/question

    CORS Issue

    You would encounter cors since the client is not part of the express application.

    So you must include the following code your express app.

    const cors = require('cors'); // npm i -s cors - to install it in your express app
    app.use(cors());
    

    To filter origins and do more stuff you refer the docs