XHR pre-flight with Express Node.js - node.js

I'm trying to make a "MEVN" application (MongoDB, Express, Vue, NodeJs).
On the client side, I have a vue component which provides a form to create a post. The post is basically a title and a description. So I have something like this :
methods: {
async addPost () {
await PostsService.addPost({
title: this.title,
description: this.description
})
this.$router.push({ name: 'Posts' })
}
}
My PostsService is a helper to handle posts :
import Api from '#/services/Api'
export default {
addPost (params) {
return Api().post('posts', params)
},
}
My Api is a simple axios constructor :
import axios from 'axios'
export default() => {
return axios.create({
baseURL: `http://localhost:8081`
})
}
On the server side, I have an entry point :
var express = require('express')
, app = express()
app.use(require('./controllers'))
app.listen(8081, function() {
console.log('Listening on port 8081...')
})
Which initiate a controller loader :
var express = require('express')
, router = express.Router()
router.use('/posts', require('./posts'))
module.exports = router
The post controller looks like this :
var express = require('express')
, router = express.Router()
, Post = require('../models/post')
// Add new post
router.post('/posts', function(req, res) {
var title = req.title;
var description = req.description;
post = Post.create(title, description);
if(post) {
res.send({flag: 'SUCCESS', content: post})
} else {
res.send({flag: 'ERROR', content: 'Failed to create the post'})
}
})
module.exports = router
As you can see there is some action with models/post which will make a db connection and save the post.
When I start my server using npm start, I have the confirmation I'm listenning on port 8081.
When I call the addPost() function, I get two XHR requests :
First XHR
Request URL: http://localhost:8081/posts
Request Method: OPTIONS
Status Code: 204 No Content
Remote Address: [::1]:8081
Referrer Policy: no-referrer-when-downgrade
Access-Control-Allow-Headers: content-type
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 0
Date: Sun, 15 Jul 2018 18:20:01 GMT
Vary: Access-Control-Request-Headers
X-Powered-By: Express
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en,fr-FR;q=0.9,fr;q=0.8,en-US;q=0.7,en-GB;q=0.6
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Connection: keep-alive
Host: localhost:8081
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36
Second XHR
Request URL: http://localhost:8081/posts
Request Method: POST
Status Code: 404 Not Found
Remote Address: [::1]:8081
Referrer Policy: no-referrer-when-downgrade
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 145
Content-Security-Policy: default-src 'self'
Content-Type: text/html; charset=utf-8
Date: Sun, 15 Jul 2018 18:20:01 GMT
X-Content-Type-Options: nosniff
X-Powered-By: Express
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en,fr-FR;q=0.9,fr;q=0.8,en-US;q=0.7,en-GB;q=0.6
Connection: keep-alive
Content-Length: 35
Content-Type: application/json;charset=UTF-8
Host: localhost:8081
Origin: http://localhost:8080
Referer: http://localhost:8080/posts/new
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36
{title: "test", description: "test"}
The second XHR fails and tells me : Cannot POST /posts
Can you explain me what happens and how to fix it ?
Thanks

Your route handler is for /posts/posts so you don't actually have a route handler for just /posts. The first part of the /posts/posts path comes from here:
router.use('/posts', require('./posts'))
The second /posts that adds onto the first comes from:
router.post('/posts', function(req, res) {...}
These two are additive so the URL you have a handler for is /posts/posts.
I'm guessing that the OPTIONS request works because you have some generic CORS middleware installed that is approving all routes when requested with OPTIONS. The second request fails because there is no route handler for just /posts, only one for /posts/posts.
You can fix this by either changing this:
router.use('/posts', require('./posts'))
to:
router.use(require('./posts'))
Or, by changing this:
router.post('/posts', function(req, res) {..}
to this:
router.post('/', function(req, res) {..}
Which ones to choose depends upon whether you want every route on your post controller router to inherit /posts as the root of the path or whether you want to define multiple routes at the top level in your post controller router.

Related

Express/Nodejs received undefined json from angular using post method

What I've done: I tried to post json from angular to nodejs but it failed. I tried to search for solution of "undefined post nodejs json" and "options instead of post", and changed my header to exclude the [option], also tried to parse the json data I tried to set, but nothing is useful.
The problem: In the angular code below, I did not get response, there was no output of the "console.log()", I wonder what is wrong. And the json.body I reuqired in app.js returns "undefined"
I checked the browser, first it sends [options] request and gets 200OK, but next when it sends [post], but no status is returned :
OPTIONS /api/postData HTTP/1.1
Host: 127.0.0.1:3000
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Referer: http://127.0.0.1:4200/
Origin: http://127.0.0.1:4200
Connection: keep-alive
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
POST http://127.0.0.1:3000/api/postData
Host: 127.0.0.1:3000
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0
Accept: application/json, text/plain, */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/json
Content-Length: 27
Origin: http://127.0.0.1:4200
Connection: keep-alive
Referer: http://127.0.0.1:4200/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
Is there any mistake in the code?
angular code: component.ts
this.http.post<any>("http://127.0.0.1:3000/api/postData", loc_json).subscribe(response =>{
console.log("Post to nodejs from angular")
console.log(response);
});
nodejs using express: app.js
const express = require('express')
const api_helper = require('./API_helper')
const port = 3000
const cors = require('cors')
const app = express()
app.use(cors())
// allowCrossDomain = function(req, res, next) {
// res.header('Access-Control-Allow-Origin', '*');
// res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
// res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
// if ('OPTIONS' === req.method) {
// res.send(200);
// } else {
// next();
// }
// };
// app.use(allowCrossDomain);
app.get('/', (req, res, next) => {
res.send("wtffffffffffffffffff");//send to the page
})
app.post('/getAPIResponse', (req, res, next) => {
api_helper.make_API_call('https://jsonplaceholder.typicode.com/posts')
.then(response => {
res.json(response)
})
.catch(error => {
res.send(error)
})
})
//angular --> nodejs
app.post('/api/postData', function(request, response){
//console.log("postData on nodejs 3000");
// const loc_nodejs = req.body;
// console.log("loc_nodejs.loc ", loc_nodejs);
console.log(request.body);
})
app.listen(port, () => console.log(`NodeJS App listening on port ${port}!`))
Because you are using Sec-Fetch-Mode: cors in your request, then your API in Express needs to have CORS enabled and configured correctly. If you are doing local development, I would turn CORS off and enable it in production, but you also may be running two processes for the Angular app and the Express app. In that case, follow the documentation for Express to enable CORS on the API via the documentation below.
https://expressjs.com/en/resources/middleware/cors.html
I added these in my code and they appeared deprecated in the pic, but it does work
const bp = require('body-parser');
app.use(bp.json())
app.use(bp.urlencoded({ extended: true }))\

Express.js API fails to receive cookies from front end

In a React.js app I am using the js-cookie library to set 2 cookies. I am able to log the cookies to the console. I also see both cookies in a chrome extension, and the keys/values match.
I am sending the cookies via a fetch request that has a key for credentials: 'include'
async function requestAllAccountData() {
const allAccountDataEndpoint = buildUrl(REACT_APP_HTTPS_BACKEND_DOMAIN, {
path: '/account-data/all'
});
console.log('allAccountDataEndpoint', allAccountDataEndpoint);
try {
const response = await fetch(allAccountDataEndpoint, {
method: 'get',
mode: 'cors',
credentials: 'include', // for cookie passage to back end
headers: {
'content-type': 'application/json',
},
});
const allAccountData = await response.json();
console.log('allAccountData',allAccountData);
return allAccountData;
} catch (error) {
throw new Error(error);
}
}
An express endpoint with the following code fails to print the cookie values. Later in the code the lack of cookie keys/values sends control down a sad path.
router.get('/all', async (req: Request, res: Response) => {
console.log('req.cookies', req.cookies);
// [Object: null prototype] {}
console.log('number of cookies keys', Object.keys(req.cookies).length);
// 0
In server.ts I am bringing in the cookie-parser package as an invoked middleware:
const corsConfigured = cors({
credentials: true, // this setting should accept cookies
origin: true,
});
server
.use(corsConfigured)
.use(cookieParser())
.use(Express.json())
.use('/account-data', accountDataRouter);
// ^ this is the router shown in the prior code sample
What am I failing to do to cause the cookies not to be visible inside the route handler?
The cookies have no special options set on them.
Update: Request Information
In Google Chrome I do not see a header for the cookies in either the GET or OPTIONS request:
Request Method: GET
Status Code: 401
Remote Address: [2600:1f16:d83:1201::6e:1]:443
Referrer Policy: strict-origin-when-cross-origin
access-control-allow-credentials: true
access-control-allow-origin: http://localhost:3000
content-length: 33
content-type: application/json; charset=utf-8
date: Thu, 01 Oct 2020 16:05:30 GMT
etag: W/"21-EAAxQ8w9ulq766ONDoxsOSjUMSY"
status: 401
vary: Origin
x-powered-by: Express
:authority: asanarepeater.ngrok.io
:method: GET
:path: /account-data/all
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9,th;q=0.8
content-type: application/json
origin: http://localhost:3000
referer: http://localhost:3000/
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36
.
Request Method: OPTIONS
Status Code: 204
Remote Address: [2600:1f16:d83:1201::6e:1]:443
Referrer Policy: strict-origin-when-cross-origin
access-control-allow-credentials: true
access-control-allow-headers: content-type
access-control-allow-methods: GET,HEAD,PUT,PATCH,POST,DELETE
access-control-allow-origin: http://localhost:3000
content-length: 0
date: Thu, 01 Oct 2020 16:05:28 GMT
status: 204
vary: Origin, Access-Control-Request-Headers
x-powered-by: Express
:authority: asanarepeater.ngrok.io
:method: OPTIONS
:path: /account-data/all
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9,th;q=0.8
access-control-request-headers: content-type
access-control-request-method: GET
origin: http://localhost:3000
referer: http://localhost:3000/
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36

CORS is enabling for login and next api and failing for all other APIs

I am implementing a React application and node server as a backend. Recently I have updated my chrome version. And also updated some APIs but I haven't done any changes regarding CORS. But from Yesterday login request and the next request is getting success (I mean requests on the load of the application) after that any request that is fired due to event in the browser is failing.
All requests on load of the applications is a success when I go to any other routes by clicking on link API calls in that route Component are failing. I don't understand the reason for getting success on load and getting CORS error on any event-based API request?
My options req/res headers are
Request:
Request URL: http://localhost:4000/apps
Request Method: OPTIONS
Status Code: 204 No Content
Remote Address: [::1]:4000
Referrer Policy: no-referrer-when-downgrade
Res Headers:
Access-Control-Allow-Headers: authorization,orgid
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 0
Date: Sun, 02 Aug 2020 06:58:37 GMT
Strict-Transport-Security: max-age=15552000; includeSubDomains
Vary: Access-Control-Request-Headers
X-Content-Type-Options: nosniff
X-DNS-Prefetch-Control: off
X-Download-Options: noopen
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Req Headers:
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Access-Control-Request-Headers: authorization,orgid
Access-Control-Request-Method: GET
Connection: keep-alive
Host: localhost:4000
Origin: http://localhost:3000
Referer: http://localhost:3000/apps/list
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36 Edg/84.0.522.52
This request is always getting success.
But I have another request (this req is failing with CORS)
Req:
Request URL: http://localhost:4000/rs
Request Method: OPTIONS
Status Code: 204 No Content
Remote Address: [::1]:4000
Referrer Policy: no-referrer-when-downgrade
res Headers"
Access-Control-Allow-Headers: appid,authorization
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 0
Date: Sun, 02 Aug 2020 06:59:21 GMT
Strict-Transport-Security: max-age=15552000; includeSubDomains
Vary: Access-Control-Request-Headers
X-Content-Type-Options: nosniff
X-DNS-Prefetch-Control: off
X-Download-Options: noopen
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Req Headers:
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Access-Control-Request-Headers: appid,authorization
Access-Control-Request-Method: GET
Connection: keep-alive
Host: localhost:4000
Origin: http://localhost:3000
Referer: http://localhost:3000/apps/rs/list
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36 Edg/84.0.522.52
I have enabled CORS in node API like,
let cors = require('cors')
app.use(cors());
app.use(function (req, res, next) {
next();
});
//routes start from here
Error message:
Access to fetch at 'http://localhost:4000/rs' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Failed GET request headers,
Request URL: http://localhost:4000/rs
Referrer Policy: no-referrer-when-downgrade
res Headers:
Connection: close
req Headers:
Accept: application/json
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,te;q=0.8
Authorization: Bearer eyJpZCI6IjVkNTE5NjFlNWMzMDM1NDlkNDYwZjk
Connection: keep-alive
Content-Type: application/json
Host: localhost:4000
orgId: 5dca073d4b044330e44e7946
Origin: http://localhost:3001
Referer: http://localhost:3001/apps/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*"); // "*" means allow connection from any request url.
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
You can change the * with the allowed url.
Or try this cors tutorial make sure to whitelist your request url. In your case 'http://localhost:3000'
// Set up a whitelist and check against it:
var whitelist = ['http://localhost:3000']
var corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}
// Then pass them to cors:
app.use(cors(corsOptions));
You don't require all that to send an http request. This is a basic example.
It should be like this:
Server.js
const express = require('express');
const cors = require('cors');
var app = express();
app.use(cors());
app.get('/', function(req, res) {
res.json({'Hello':'World'});
});
app.listen(3000);
Client..html
<html>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$.get("http://localhost:3000/", function(response) {
console.log(resposne);
});
</script>
</html>

CORS error but only on POST request, despite cors config (GET have no issue)

I use a nodejs express server.
Despite allowing the host, I still have an CORS error
" No 'Access-Control-Allow-Origin' header is present on the requested
resource."
but only for the POST endpoint. The "GET" have no issue.
Both (GET and POST) endpoint are allowed for my client-browser:
My server:(running on http://serverURL)
var whitelist = ['http://localhost:4200', 'http://someOtherDeployUrl.com']
var corsOptionsDelegate = function (req, callback) {
var corsOptions;
if (whitelist.indexOf(req.header('Origin')) !== -1) {
corsOptions = {origin: true} // reflect (enable) the requested origin in the CORS response
} else {
corsOptions = {origin: false} // disable CORS for this request
}
corsOptions.methods= "GET,HEAD,PUT,PATCH,POST,DELETE";
callback(null, corsOptions) // callback expects two parameters: error and options
}
router.post('/score', cors(corsOptionsDelegate), function (req, res, next) {
...
res.status(200).send('Ok');
});
router.get('/scores', cors(corsOptionsDelegate), function (req, res, next) {
res.status(200).send(scores);
});
The client ( angular 9) : (running on localhost:4200)
public saveScore(player, score) {
console.log("save score")
let objectObservable = this.http.post("http://serverURL/score", {
player: player,
score
}).subscribe(
data => console.log('success', data),
error => console.log('oops', error)
);
return objectObservable
}
public getScores() {
return this.http.get("http://serverURL/scores");
}
any idea why it's don't work?
The whole request/response of the GET:
Response:
Referrer Policy: no-referrer-when-downgrade
Access-Control-Allow-Origin: http://localhost:4200
Content-Length: 2
Content-Type: application/json; charset=utf-8
Date: Sun, 14 Jun 2020 14:42:35 GMT
Etag: W/"2-l9Fw4VUO7kr8CvBlt4zaMCqXZ0w"
Server: Cowboy
Vary: Origin
Via: 1.1 vegur
X-Powered-By: Express
Request:
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate
Accept-Language: en,en-US;q=0.9,fr-FR;q=0.8,fr;q=0.7
Connection: keep-alive
DNT: 1
Host: serverUrl
If-None-Match: W/"2-l9Fw4VUO7kr8CvBlt4zaMCqXZ0w"
Origin: http://localhost:4200
Referer: http://localhost:4200/menu
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36
The whole response/request for the (failing) POST
Response:
Allow: POST
Connection: keep-alive
Content-Length: 4
Content-Type: text/html; charset=utf-8
Date: Sun, 14 Jun 2020 14:30:00 GMT
Etag: W/"4-Yf+Bwwqjx254r+pisuO9HfpJ6FQ"
Server: Cowboy
Via: 1.1 vegur
X-Powered-By: Express
Request:
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en,en-US;q=0.9,fr-FR;q=0.8,fr;q=0.7
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Connection: keep-alive
Host: serverUrl
Origin: http://localhost:4200
Referer: http://localhost:4200/menu
Sec-Fetch-Mode: cors
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36
Try enabling CORS preflight (OPTIONS) handling for your route.
When you need your route to handle so-called complex CORS operations, you must add a OPTIONS route handler. The browsers send an extra request, an OPTIONS request.
Why is this extra complex? Because cybercreeps.
Add this route handler. Right before your post handling is a good place for it.
router.options('/score', cors())

Nodejs API : CORS seems to be enabled by default

Here is my problem: I have a site exemple.com and a node server where is my API running on exemple.com:3000. I want my API to be accessible only by exemple.com.
So I thought that Same-Origin Policy would have block every request from every site except mine if I send in the response the header : Access-Control-Allow-Origin: https:exemple.com.
The problem is that if I call the url : http://exemple.com:3000/api/v1/test/search on another site, I have the error:
Failed to load https://exemple:3000/api/v1/test/search: The 'Access-Control-Allow-Origin' header has a value 'https://exemple.com' that is not equal to the supplied origin. Origin 'http://randomsite.com' is therefore not allowed access.
But in the network tab, I have the response with a 200 status and all the results.
How is it possible to have the error and the result at the same time ? Here is my code :
app.js
const corsApiOptions = {
origin: 'https://exemple.com',
originSuccessStatus: 200,
};
app.use('/api/v1', cors(corsApiOptions), api);
routes/api.js
const express = require('express'); const mongoose =
require('mongoose'); const mongoosastic = require('mongoosastic');
const AssoSchema = require('../schemas/assoSchema');
const router = express.Router();
router.post('/assos/search', (req, res) => { let { query } =
req.body; if (query && query.length > 0) {
query = query
.split(' ')
.map(el => `${el}~`)
.join(' ');
mongoose.connect('mongodb://localhost/mydb');
AssoSchema.plugin(mongoosastic);
const Asso = mongoose.model('asso', AssoSchema, 'assos');
Asso.search(
{
query_string: { query },
},
{ hydrate: true },
(err, results) => {
if (err) res.json({ error: err });
res.json(results.hits.hits);
},
); } else res.json(''); });
module.exports = router;
Here are the results if I make an ajax request from the console of randomsite.com
//General
Request URL: https://exemple.com:3000/api/v1/test/search
Request Method: POST
Status Code: 200 OK
Remote Address: X.X.X.X:3000
Referrer Policy: no-referrer-when-downgrade
//Response Headers
Access-Control-Allow-Origin: https://exemple.com
Connection: keep-alive
Content-Length: 10022
Content-Type: application/json; charset=utf-8
Date: Fri, 30 Mar 2018 10:52:25 GMT
ETag: W/"2726-3/3tY5WvDTtyKm4KPBifg2dP7mI"
Vary: Origin
X-Powered-By: Express
//Request Headers
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7
Connection: keep-alive
Content-Length: 21
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Host: exemple.com:3000
Origin: http://randomsite.com
Referer: http://random.site.com/
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36
//Form Data
query: random search
And in the preview tab I can see all my 10 results in json.
I want my api to accessed only from exemple.com, can someone help me on that ?
But in the network tab, I have the response with a 200 status and all the results.
How is it possible to have the error and the result at the same time ?
The Same Origin Policy prevents JavaScript (embedded in a web page on a different origin) from reading the data in the response.
It is enforced by the browser.
It doesn't prevent the request being made.
It doesn't prevent the browser from getting the response.
It doesn't prevent the owner of the browser from seeing the response through other means (such as the Network tab) and even if it did, they could just make the HTTP request using another tool, such as cURL.
CORS allows a server to tell the browser to relax the Same Origin Policy and allow the JavaScript access to the data.
I want my api to accessed only from exemple.com, can someone help me on that ?
This isn't possible.
JavaScript on other origins won't be able to read the data directly, but it does nothing for non-JS approaches or indirect (e.g. via a proxy) approaches.

Resources